当以下代码执行时,它显示无输出。谁能告诉我哪里出错了?
html文件:
<head>
<script type = "text/javascript">function ajax_get_json()
{
var hr = new XMLHTTPRequest();
hr.open("GET","mylist.json",true);
hr.setRequestHeader("Content-type :application/json",true);
hr.onread
ystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var data = JSON.parse(hr.responseText);
var results=document.getElementById("results");
results.innerHTML = data.user;
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type = "text/javascript">ajax_get_json();</script>
</body>
json文件: {“user”:“John”,“age”:22,“country”:“US”}
答案 0 :(得分:0)
XMLHTTPRequest()必须是XMLHttpRequest()
。 JavaScript文件如下所示:
function request() {}
request();
HTML
<script src="file.js"></script>
使用var data = JSON.parse(hr.responseText);
,您拥有对象。
浏览对象:
for(var key in obj) {}
在 innerHTML 中和存储键和obj [key]以查看结果。 完整的JavaScript文件:
function request() {
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText); // object
var results = document.getElementById("results");
results.innerHTML = "";
for(var key in data) {
results.innerHTML += key + " " + data[key] + "<br>";
}
}
}
hr.open("GET", "mylist.json", true);
hr.send();
results.innerHTML = "requesting...";
}
request();
(请更改问题的标题。具体! How to ask)