使用JavaScript从URL获取JSON数据并将其放入变量中

3
我可以帮您翻译成中文:

我有一个JSON数据的URL,我想用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();

如果有新的方法,请展示。

它在哪方面不起作用? - Nick
你尝试过让get()返回obj吗? - bloo
看起来不错!你如何检查它是否工作? - hoangdv
3个回答

4

你需要将代码包装在async/await模式中。

在你的代码中,你没有返回任何东西。


注:Original Answer翻译成“最初的回答”未能理解其上下文,因此未翻译。
  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会在完成后返回结果,并且下一行代码会立即运行,因此tags变量是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>


如何将其放入外部变量而不是console.log - word
我更新了答案,你需要在async块内处理你的代码,如果你尝试使用下面的代码,它将是未定义的。异步返回结果时,下一行代码会立即运行。 - Hien Nguyen
ERR_CERT_DATE_INVALID 可能是服务器拒绝获取数据。 - Hien Nguyen

0

您可以使用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();



0

您的调用没有异步解析,因此标记为空。

这是使用 fetch 的标准方式:

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


它不是HTTPS,如果你从另一个服务器调用它,你需要启用CORS。 - mplungjan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接