从PHP编码的JSON文件中提取数据

时间:2016-05-07 22:48:44

标签: javascript php json ajax

我已经从各种文章和教程中拼凑了下面的内容,但我对PHP,JSON和Javascript非常陌生。

我有一个ID为id" playerName"我需要每10秒更新一次。

问题:

1)我正在做这件事"对"或者有更简单的方法吗? 2)如果我想从JSON文件更新2个具有不同值的不同div,我只需复制完整的" ajax_get_json"功能

我的json文件(又名:data.php):

<?php
header("Content-Type: application/json"); // set the content type to json
$jsonData = '{
    "u1":{ "name":"Bob", "age":"25", "country":"United States" }
}';
echo $jsonData;
?>

我的html文件:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax_get_json(){
    // Create our XMLHttpRequest object
    var results = document.getElementById("playerName");
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    hr.open("GET", "data.php", true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/json");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var data = JSON.parse(hr.responseText);
            results.innerHTML = "";
            for(var obj in data) {
                results.innerHTML += data[obj].name;
                setTimeout(ajax_get_jsonStatus, 10000);
            }
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(null); // Actually execute the request
}
</script>
</head>
<body>
<div id="playerName"></div>
<script type="text/javascript">
    ajax_get_json();
</script>
</body>
</html>

我几乎在脑海中,埋没在谷歌搜索中。任何帮助表示赞赏!

大部分代码来自Adam Khoury的教程系列:https://youtu.be/wbB3lVyUvAM

1 个答案:

答案 0 :(得分:0)

避免手工构建json,它容易出错,只需将您的本机数据类型编码为json

$data = [
    "u1"=>[ "name"=>"Bob", "age"=>"25", "country"=>"United States" ]
];
echo json_encode($data); 

不要为GET请求设置内容类型标头,您实际上不能通过GET请求(通过XMLHttpRequest)中的内容主体。您可能会将响应内容类型与请求混在一起?
您可以根据预期的响应设置一个值,即responseType

如果您想更新更多div,只需将数据放入响应中即可。

<?php
header("Content-Type: application/json"); // set the content type to json
$data = [
    "u1"=>[ "name"=>"Bob",    "age"=>"25", "country"=>"United States" ],
    "u2"=>[ "name"=>"Marley", "age"=>"11", "country"=>"of Jamaica" ]
];
echo json_encode($data); 
function ajax_get_json(){
    // Create our XMLHttpRequest object
    var results1 = document.getElementById("player1Name");
    var results2 = document.getElementById("player2Name");
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    hr.open("GET", "data.php", true);
    // Set response type so the browser knows what to expect and parses it for you
    hr.responseType = 'json';
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var data = this.response;
            results1.innerHTML = data['u1'].name;
            results2.innerHTML = data['u1'].name;
            setTimeout(ajax_get_jsonStatus, 10000);
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(null); // Actually execute the request
}