簡體   English   中英

從url獲取json數據,並通過JavaScript將其放入變量中

[英]Get json data from url and put it into variable by JavaScript

我在URL中有一個JSON數據,我想通過JavaScript(沒有jQuery)從URL中獲取所有JSON數據,並將其放入變量tags

JSON數據:

 [
  {
    "uniq":"AXk2_U9l"
  },
  {
    "uniq":"AX0apLOG"
  },
  {
    "uniq":"AXrGmWk4"
  },
  {
    "uniq":"AXID1Psx"
  },
  {
    "uniq":"vovs2aPlj"
  }
]

還有我的JavaScript代碼,此代碼不起作用:

 async function get() { let url = 'https://jsonware.com/json/abfe005c41c8214e22e487b8d6eff417.json' let obj = await (await fetch(url)).json(); console.log(obj); } var tags = get(); 

如果有新方法,請顯示。

您需要將代碼包裝在異步/等待模式中

在您的代碼中,您沒有返回任何內容。

  var tags;
    (async () => {
      tags = await get()
      console.log(tags)
      // handle the tags result here
    })()
    // if you try use tags here it will be undefined

async返回結果,當它完成並且下一行代碼立即運行時,標簽變量undefined

 async function get() { let url = 'https://jsonware.com/json/abfe005c41c8214e22e487b8d6eff417.json' let obj = await (await fetch(url)).json(); //console.log(obj); return obj; } var tags; (async () => { tags = await get() //console.log(tags) document.getElementById("tags").innerHTML = JSON.stringify(tags); })() 
 <div id="tags"></div> 

您可以使用XMLHttpRequest進行如下操作

 function loadJson() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var tags = JSON.parse(this.responseText); console.log(tags); } }; xhttp.open("GET", "https://jsonware.com/json/abfe005c41c8214e22e487b8d6eff417.json", true); xhttp.send(); } loadJson(); 

您的通話無法異步解決,因此標簽為空

這是使用提取的標准方法:

 fetch('https://jsonware.com/json/abfe005c41c8214e22e487b8d6eff417.json') .then( response => { if (response.status !== 200) { console.log('Looks like there was a problem. Status Code: ' + response.status); return; } // Examine the text in the response response.json().then(function(data) { console.log(data); }); }) .catch(err => console.log('Fetch Error :-S', err)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM