<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script
<script>
function kick_start(){
var xml=new XMLHttpRequest();
var url="student.json";
xml.open("GET", url, true);
xml.send();
xml.onreadystatechange=function(){
if(xml.readyState == 4 && xml.status==200){
var file=JSON.parse(xml.responseText);
var data=document.getElementById("demo");
data.innerHTML=file.Name;
}
}
data.innerHTML="Fetching Data..........";
}
</script>
<script>kick_start()</script>
</body>
</html>
JSON文件是:
{"Name":"Arman","ID":1312038;"Department":"NAME"}
我尝试了很多来运行这个HTML文件,以通过Ajax请求从JSON文件中获取数据。但有些东西是错的。我将文件保存在同一目录中。我该怎么办?
答案 0 :(得分:2)
When you're setting the data.innerHTML
to "Fetching Data", data
is not the element at that point, because it only becomes the element when the ajax completes. This will trigger an error in the console – press F12 to take a look.
To solve that, move the var data = ...
line out of the readystatechange function.
Another problem is your JSON isn't valid, you have ;
which should be a comma. You can validate it on JSONLint.