gpt4 book ai didi

javascript - 我将如何从外部 url 解析 json?

转载 作者:行者123 更新时间:2023-11-29 20:55:13 25 4
gpt4 key购买 nike

我对 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);

}

如果您需要更多详细信息,请告诉我。

关于javascript - 我将如何从外部 url 解析 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49623022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com