最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Get json data from url and put it into variable by JavaScript - Stack Overflow

programmeradmin5浏览0评论

I have a JSON data in a URL, I want to get all JSON data from the URL by JavaScript (without jQuery) and put it into variable tags.

JSON Data:

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

And my JavaScript code, this code does not work:

async function get() {
  let url = '.json'
  let obj = await (await fetch(url)).json();
  console.log(obj);
}
var tags = get();

I have a JSON data in a URL, I want to get all JSON data from the URL by JavaScript (without jQuery) and put it into variable tags.

JSON Data:

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

And my JavaScript code, this code does not work:

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

if there is a new method, please show.

Share Improve this question edited May 4, 2019 at 6:20 mplungjan 178k28 gold badges182 silver badges240 bronze badges asked May 4, 2019 at 5:42 word word 531 gold badge2 silver badges8 bronze badges 3
  • In what way does it not work? – Nick Commented May 4, 2019 at 5:49
  • have you tried making get() return obj? – bloo Commented May 4, 2019 at 6:00
  • It seem fine! How do you check it is working or not? – hoangdv Commented May 4, 2019 at 6:16
Add a ment  | 

3 Answers 3

Reset to default 4

You need wrapped your code inside async/await pattern

In your code, you did not return anything.

  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 return result when it finish and next line of code run immediately so tags variable is undefined

async function get() {
    let url = 'https://jsonware./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>

You can do it using XMLHttpRequest like as follows

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./json/abfe005c41c8214e22e487b8d6eff417.json", true);
  xhttp.send();
}
loadJson();

Your call is not resolved asynchronously so tags are empty

Here is the standard way to use fetch:

fetch('https://jsonware./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));

发布评论

评论列表(0)

  1. 暂无评论