iam在wamp服务器上测试ajax,但是它说send()是一个非常多的函数,并且我得到了空白文档。
控制台正在记录:
XHR完成加载:GET“http://localhost/json/main.json”。(匿名函数)@ widget.js:21(xhr.send();
)
我的htmL:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajax</title>
<link rel="stylesheet" href="css/style.css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<div id="employees">
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/widget.js"></script>
<script type="text/javascript" src="json/main.JSON"></script>
</body>
</html>
json对象:
[
{
"name": "Joe Consterdine",
"workstatus": true
},
{
"name": "Roberto Baggio",
"workstatus": true
},
{
"name": "Michael Smith",
"workstatus": false
},
{
"name": "Darren Huckerby",
"workstatus": true
},
{
"name": "Dean Blackwell",
"workstatus": false
},
{
"name": "Neil Sullivan",
"workstatus": false
},
{
"name": "Mark Fish",
"workstatus": true
},
{
"name": "Dean Holdsworth",
"workstatus": true
}
]
我的js代码:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.onreadystate === 4){
var employees = JSON.parse(xhr.responseText);
var statusHTML = '<ul class="bulleted">';
for(var i = 0; i<employees.length; i++ ){
if(employees[i].workstatus === true){
statusHTML += '<li class="in">';
}else{
statusHTML += '<li class="out">';
}
statusHTML += employees[i].name + '</li>';
}
statusHTML += '</ul>';
document.getElementById('employees').innerHTML = statusHTML;
}
}
xhr.open('GET', 'json/main.json');
xhr.send();
答案 0 :(得分:1)
它是if(xhr.readyState ==4)
而不是你拥有的
您还应该检查xhr.status
onreadystatechange
所以,你的代码将是
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var employees = JSON.parse(xhr.responseText);
var statusHTML = '<ul class="bulleted">';
for (var i = 0; i < employees.length; i++) {
if (employees[i].workstatus === true) {
statusHTML += '<li class="in">';
} else {
statusHTML += '<li class="out">';
}
statusHTML += employees[i].name + '</li>';
}
statusHTML += '</ul>';
document.getElementById('employees').innerHTML = statusHTML;
}
};
xhr.open('GET', 'json/main.json');
xhr.send();
我更喜欢使用onload / onerror
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var employees = JSON.parse(xhr.responseText);
var statusHTML = '<ul class="bulleted">';
for (var i = 0; i < employees.length; i++) {
if (employees[i].workstatus === true) {
statusHTML += '<li class="in">';
} else {
statusHTML += '<li class="out">';
}
statusHTML += employees[i].name + '</li>';
}
statusHTML += '</ul>';
document.getElementById('employees').innerHTML = statusHTML;
};
xhr.onerror = function(e) {
console.log(e);
};
xhr.open('GET', 'json/main.json');
xhr.send();
但onload / onerror可能在旧版浏览器中无法使用,即IE