我对js比较陌生。我希望能够使用纯JavaScript从外部URL解析json。目前我正在使用
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
function statsget() {
var uname = document.getElementById("nameget").value;
var data = getJSON(`https://www.reddit.com/user/${uname}/circle.json`);
var stats = JSON.parse(data);
alert(data.is_betrayed);
}
但是,这是行不通的。有人可以帮我吗?谢谢!
首先,您忘记了将回调函数传递给getJSON作为第二个参数,应该在xhr返回数据时调用该参数。其次,当您从服务器请求JSON文件并将responseType设置为JSON时,无需将数据解析为json,这将自动为您完成。
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
function yourCallBackFunction(err, data){
if(err){
//Do something with the error
}else{
//data is the json response that you recieved from the server
}
}
function statsget() {
var uname = document.getElementById("nameget").value;
var data = getJSON(`https://www.reddit.com/user/${uname}/circle.json`, yourCallBackFunction);
}
如果您需要更多详细信息,请告诉我。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句