[英]I am trying to get the data from json in html. I don't want to use Ajax because
I ma learning XMLHttpRequest
. 我正在学习
XMLHttpRequest
。 JSON data is not loading. JSON数据未加载。 For some reason I am not getting the value of my json data.
由于某种原因,我没有得到json数据的值。 My code
我的密码
function foo() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "data.json",true);
httpRequest.send();
var abc = httpRequest.responseText;
}
My Json Data 我的Json资料
[
{
ID : 0,
VALUE : "United State"
},{
ID : 1,
VALUE : "United Kingdom"
},{
ID : 2,
VALUE : "Afghanistan"
},{
ID : 3,
VALUE : "Aland Islands"
},{
ID : 4,
VALUE : "Albania"
}
]
What I am making wrong here. 我在这里做错了。
You are missing an onreadystatechange
event handler, which is how you actually get the data: 您缺少一个
onreadystatechange
事件处理程序,它实际上是如何获取数据的方式:
function foo() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "data.json",true);
httpRequest.onreadystatechange = function () {
if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
console.log(httpRequest.responseText);
}
};
httpRequest.send();
}
If you need to work with that data outside of your function, you can use the callback pattern: 如果您需要在函数之外使用该数据,则可以使用回调模式:
function foo(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "data.json",true);
httpRequest.onreadystatechange = function () {
if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
// trigger your callback function
callback(httpRequest.responseText);
}
};
httpRequest.send();
}
foo(function(data) {
console.log(data);
});
function foo(callback) {
return new Promise(function(resolve, reject) {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "data.json",true);
httpRequest.onreadystatechange = function () {
if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
// trigger your callback function
resolve(httpRequest.responseText);
}
};
httpRequest.send();
});
}
foo().then(function(data) {
console.log(data);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.