简体   繁体   中英

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

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.com/json/abfe005c41c8214e22e487b8d6eff417.json' let obj = await (await fetch(url)).json(); console.log(obj); } var tags = get(); 

if there is a new method, please show.

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.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> 

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.com/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.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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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