簡體   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