我如何从外部网址解析json? [英] How would I parse json from an external url?

查看:112
本文介绍了我如何从外部网址解析json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对js比较陌生.我希望能够使用纯JavaScript从外部URL解析json.目前,我正在使用

I am relatively new to js. I want to be able to parse json from an external url using pure javascript. At the moment I am using

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);
 }

但是这不起作用.有人可以帮我吗?谢谢!

this however is not working. Could anyone help me with this? Thanks!

推荐答案

首先,您忘了将回调函数传递给getJSON作为第二个参数,应该将其称为 当您的xhr返回数据时. 其次,当您从服务器请求JSON文件并将responseType设置为JSON时,无需将数据解析为json,这将自动为您完成.

First of all you forgot to pass callback function to getJSON as second parameter, which is supposed to be called when your xhr returns with the data. Second, you do not need to parse data to json when you are asking for JSON file from server and setting responseType to JSON, this would be automatically done for you.

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

 }

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

Let me know if you need more details on this.

这篇关于我如何从外部网址解析json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆