如何使用Javascript

时间:2018-05-28 18:27:11

标签: javascript json xmlhttprequest

我正在尝试创建一个用于天气预报的小型网站。当向accuWeather发送请求以获取JSON时,我无法获得响应。我已经检查了几次请求,并且它正常工作。有人可以指出我的代码有什么问题,所以我可以修复它吗?另外,如果你回答,你可以使用Javascript而不是使用JQuery 链接:

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

这是我研究javascript的项目。 apiKey也是公开的。

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

我将不胜感激。

3 个答案:

答案 0 :(得分:2)

一些事情。首先,您需要使用send()实际发送请求。其次,如果您正在执行异步请求,则需要添加一个侦听器来处理响应:

request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200)
      console.log(request.response);
  };

  request.send(null);

如果您不想让它异步,您可以随时将false作为第二个参数传递给open()来电,但我们强烈建议不要这样做,因为它会阻止通话。

随意阅读XMLHttpRequests here for more options

更多内容

这是working example

答案 1 :(得分:2)

  

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

您可能需要在数据上使用JSON.parse

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

答案 2 :(得分:0)

你应该尝试做这样的事情:

<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);
                request.send();
                //console.log(request.response);
            }
            window.addEventListener("load",start,false);
        </script>
</head>
<body>

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

或类似的东西:

<html>
<head>
        <meta charset="utf-8"/>
        <title>getting</title>
        <script>
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                // Action to be performed when the document is read;
                }
            };
            xhttp.open("GET", "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true", true);
            xhttp.send();
            window.addEventListener("load",start,false);
        </script>
</head>
<body>

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