如何从外部 url 解析 json?

Tec*_*Hax 5 javascript json

我对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);
 }
Run Code Online (Sandbox Code Playgroud)

然而这不起作用。有人能帮我解决这个问题吗?谢谢!

小智 3

首先,您忘记将回调函数作为第二个参数传递给 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);

 }
Run Code Online (Sandbox Code Playgroud)

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