简体   繁体   English

使用javascript从URL读取JSON数据

[英]Reading JSON data from a url using javascript

I want to read data from this link http://starlord.hackerearth.com/gamesext . 我想从此链接http://starlord.hackerearth.com/gamesext读取数据。 I went through this https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON and was able to obtain data from https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json . 我经历了这个https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON ,并能够从https://mdn.github.io/learning-area/javascript/获取数据oojs / json / superheroes.json Trying similar approach for getting data from http://starlord.hackerearth.com/gamesext is not working for me. 尝试类似的方法从http://starlord.hackerearth.com/gamesext获取数据对我不起作用。 This is how I tried: 这是我尝试的方法:

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"];
    }

I would want to know is that data in JSON and how to get it? 我想知道的是JSON中的数据以及如何获取它?

Try using the JSON.parse() method: 尝试使用JSON.parse()方法:

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

This will turn valid JSON into a javascript object that can be accessed as you are trying to do below. 这会将有效的JSON转换为一个javascript对象,可以在您尝试执行以下操作时对其进行访问。

This works perfectly fine for me: 这对我来说很好用:

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

Give it a try! 试试看!

Using fetch this is pretty simply. 使用fetch非常简单。

Below is an example. 下面是一个例子。

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

just put request.send(); 只是把request.send(); after all the code you provided. 毕竟您提供了代码。

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

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