Search code examples
javascriptjsonxmlhttprequest

How to fetch JSON using Javascript


I am trying to create a small website for weather forecasting. When sending a request to accuWeather to get JSON, I cannot get a response. I have checked the request a few times, and it works normally. Could someone point out what wrong in my code so I can fix it? In addition, If you answer, Can you use Javascript instead of using JQuery Link:

http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true

This is my project for studying javascript. apiKey is public also.

<html>
<head>
        <meta charset="utf-8"/>
        <title>getting</title>
    <script>

        function start(){
            //console.log("asdasd");
            var requestURL = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true" ;
            var request = new XMLHttpRequest();
            console.log(request);
            request.open('GET', requestURL);
            //console.log(request.response);
        }
        window.addEventListener("load",start,false);
    </script>
</head>
<body>

    <div id="loading"></div>
</body>
</html>

I will appreciate any help.


Solution

  • https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

    Chaining promises with then and catch

    You may need to use JSON.parse on your data

    var requestURL = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true";
    
    
    //ES5
    function XMLrequest() {
      var request = new XMLHttpRequest();
      request.open('GET', requestURL, true);
      request.onreadystatechange = function() {
        if (request.readyState === 4) {
          console.log('XML', request.response);
        }
      }
      request.send();     
    }
    
    //ES6
    function getWithFetch() {
      fetch(requestURL)
        .then(res => {
          console.log('fetch', res)
        })
        .catch(err => {
          console.log(err, 'fetch fail')
        })
    }
    
    // ES7
    async function getWithAsycAwait() {
      try {
        const data = await fetch(requestURL);
        console.log('await', data)
      } catch(e) {
        console.log(e, 'await fail')
      }
    }
    
    getWithAsycAwait()
    getWithFetch()
    XMLrequest()