私は様々な記事やチュートリアルから以下をまとめましたが、PHP、JSON、Javascriptの新機能は非常に新しいものです。PHPでコーディングされたJSONファイルからデータを引き出す
私は10秒ごとに更新する必要があるid "playerName"のdivを持っています。
質問:
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>
私はほとんど私の頭の上だとGoogle検索に埋葬。どんな助けもありがとう!
コードのほとんどは、アダムKhouryさんのチュートリアルシリーズから来ている:手でhttps://youtu.be/wbB3lVyUvAM
'のsetTimeout(ajax_get_jsonStatus、10000);'、どこ 'ajax_get_jsonStatus()'関数がですか?なぜ、 'for'ループの各繰り返しで' setTimeout() '関数を使用していますか? –