繁体   English   中英

使用javascript从URL读取JSON数据

[英]Reading JSON data from a url using javascript

我想从此链接http://starlord.hackerearth.com/gamesext读取数据。 我经历了这个https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON ,并能够从https://mdn.github.io/learning-area/javascript/获取数据oojs / json / superheroes.json 尝试类似的方法从http://starlord.hackerearth.com/gamesext获取数据对我不起作用。 这是我尝试的方法:

var requestURL = 'http://starlord.hackerearth.com/gamesext';
    var request = new XMLHttpRequest();
    request.open('GET', requestURL);
    request.responseType = 'json';
    request.send();
    request.onload = function() {
    var games = request.response;
    document.getElementById("para").innerHTML = "for check";//para is a paragraph id
    fun1(games);
    }
    function fun1(jsonObj){
        //getting first title
        document.getElementById("para").innerHTML = jsonObj[0]["title"];
    }

我想知道的是JSON中的数据以及如何获取它?

尝试使用JSON.parse()方法:

function fun1(jsonObj){
    //getting first title
    jsonObj = JSON.parse(jsonObj);
    document.getElementById("para").innerHTML = jsonObj[0]["title"];
}

这会将有效的JSON转换为一个javascript对象,可以在您尝试执行以下操作时对其进行访问。

这对我来说很好用:

var requestURL = 'http://starlord.hackerearth.com/gamesext';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(xhttp.response[0].title)  # LittleBigPlanet PS Vita
    }
};
xhttp.open("GET", requestURL);
xhttp.responseType = 'json';
xhttp.send();

试试看!

使用fetch非常简单。

下面是一个例子。

 const url = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; async function getData() { const json = await (await fetch(url)).json(); console.log(json); } getData(); 

只是把request.send(); 毕竟您提供了代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM