当我将函数hr.open("POST or Get", "URL", "Boolean")
与.json
文件一起使用时,它可以正常工作。当我使用.php
文件时,我似乎无法打开.php
文件,但我不知道会发生什么。
这是我的HTML代码。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax_get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("GET", "555.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
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].user+" is "+data[obj].age+" and lives in "+data[obj].country+"<hr />";
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>
它适用于此代码,但当我将555.json
函数中的hr.open
更改为554.php
时,结果是“请求...”
这是我的PHP代码:
<?php
header ("Content-Type : application/json ");
$Jsondata = '{
"u1":{ "user":"John", "age":22, "country":"United States" },
"u2":{ "user":"Will", "age":27, "country":"United Kingdom" },
"u3":{ "user":"Abiel", "age":19, "country":"Mexico" },
"u4":{ "user":"Rick", "age":34, "country":"Panama" },
"u5":{ "user":"Susan", "age":23, "country":"Germany" },
"u6":{ "user":"Amy", "age":43, "country":"France" },
"u7":{ "user":"Pete", "age":18, "country":"Italy" },
"u8":{ "user":"Chris", "age":25, "country":"United States" },
"u9":{ "user":"Louis", "age":31, "country":"Spain" },
"u10":{ "user":"Emily", "age":38, "country":"Uraguay" },
"u11":{ "user":"Shawn", "age":52, "country":"Chile" },
"u12":{ "user":"Greg", "age":24, "country":"Romania" }
} ' ;
echo $Jsondata;
?>
这是我的JSON:
{
"u1":{ "user":"John", "age":22, "country":"United States" },
"u2":{ "user":"Will", "age":27, "country":"United Kingdom" },
"u3":{ "user":"Abiel", "age":19, "country":"Mexico" },
"u4":{ "user":"Rick", "age":34, "country":"Panama" },
"u5":{ "user":"Susan", "age":23, "country":"Germany" },
"u6":{ "user":"Amy", "age":43, "country":"France" },
"u7":{ "user":"Pete", "age":18, "country":"Italy" },
"u8":{ "user":"Chris", "age":25, "country":"United States" },
"u9":{ "user":"Louis", "age":31, "country":"Spain" },
"u10":{ "user":"Emily", "age":38, "country":"Uraguay" },
"u11":{ "user":"Shawn", "age":52, "country":"Chile" },
"u12":{ "user":"Greg", "age":24, "country":"Romania" }
}