doubleyou1001 2016-04-23 10:49
浏览 83
已采纳

使用ajax,PHP和Javascript循环访问JSON文件

I'm creating a small game where users must register or login before playing. I have a separate json file that stores already registered users.

Once a user enters their username and password into a field I make an AJAX call to retrieve the data using PHP with the intent of checking whether their details are on file. Firstly I tried sending back a JSON encoded object to parse through in Javascript. This is the code I have so far:

JSON:

{"LogIns":[
   {
    "Username":"mikehene",
    "password":"123"
   },
   {
    "Username":"mike",
    "password":"123"
   }
]
}

HTML:

<fieldset>
    <legend>Please log in before playing</legend>
    <form>
        Username: <br>
        <input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
        Password: <br>
        <input type="password" placeholder="Enter a password" id="password" name="password"><br>
        <input type="submit" value="Submit" onclick="return checkLogin();">
    </form>
</fieldset>

PHP:

<?php

$username = $_POST['username'];

$str = file_get_contents('logins.json'); // Save contents of file into a variable

$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json

echo json_encode($json);

?>

Javascript & AJAX call:

var usernamePassed = '';

function checkLogin(){
    usernamePassed = document.getElementById("username1").value;
    callAJAX();
    return false;

}

function callAJAX(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange=function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            myFunction(xhttp.responseText);
        }
    }
    xhttp.open("POST", "LogInReg.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("username=" + usernamePassed);
}


function myFunction(response) {

    var arr = response;
    var objJSON = JSON.parse(arr);
    var len = objJSON.length;

    for(var key in objJSON){
        console.log(key);
    }
}

But it only prints out "LogIns". I also tried this:

for (var i = 0; i < objJSON.length; ++i) {
                 if(objJSON[0].Username == usernamePassed){
                    console.log("found it");
                 }
                 else{
                    console.log("didn't find it!");
                 }
            }   

Therefore I tried another approach (parse the data in the PHP file) like so:

foreach ($json['LogIns'][0] as $field => $value) {
        if($json['LogIns'][0]['Username'] == $username){
            echo "Logged In";
               break;
            }
            else{
                echo "No user found";
                break;
            }
        }

But when I enter "mike" as a user name it is echoing "No user found". So I'm lost! I'm new to coding and trying to learn myself. I would love to learn how to do it both methods (i.e. PHP and Javascript).

Everything I've found online seems to push toward JQuery but I'm not quite comfortable/good enough at JQuery yet so would like to gradually work my way up to that.

I haven't even got to the register a user yet where I'm going to have to append another username and password on registration.

Any help would be GREATLY appreciated.

Thanks in advance

  • 写回答

1条回答 默认 最新

  • duanhoupeng6642 2016-04-23 11:12
    关注

    Try this

     $json = json_decode($str, true);
     $password = $_POST['password'];
    
            foreach($json['LogIns'] as $res)
            {
                if($res['Username']==$username && $res['password']==$password)
                {
                    echo json_encode($res['Username']);
                   //echo 'user found'; 
                }
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘