简体   繁体   English

没有获得对XMLHTTPRequest的响应

[英]didn't get response for XMLHTTPRequest

I try to get weather info from a weather API, everything seems to be working fine but I don't know why I don't get any response, the URL is Working 我尝试从天气API获取天气信息,但一切似乎都正常,但我不知道为什么我没有收到任何回复,URL正常

  //get  Response to weather status based on latitude on longitude positions
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {

            var lat = position.coords.latitude;
            var lon = position.coords.longitude;
            var apiKey = "d64b6f0e97c598ccf0f03718d1690fcc";
            var url = "api.openweathermap.org/data/2.5/weather?lat="
            var URL = url + lat + "&lon=" + lon + "&APPID=" + apiKey;
            console.log(URL);
            var xhr = new XMLHttpRequest();
            xhr.open("GET", URL, true);
            xhr.send();
            xhr.onload = function() {
                if (xhr.status == 200) {
                    document.getElementById("title").innerHTML = this.responseText;
                }
            }
        });

    } else {
        alert("Error");
    }

Open the developer tools in your browser. 在浏览器中打开开发人员工具。

Look at the Console. 查看控制台。 See if there are error messages. 查看是否有错误消息。

Look at the Network tab. 查看网络标签。 See if the request is being made, if it is being made to where you expect, and if it gets the response you expect. 查看是否正在发出请求,是否在期望的位置发出请求以及是否获得了期望的响应。

 var url = "api.openweathermap.org/data/2.5/weather?lat=" 

You forgot the scheme from the URL. 您从URL忘记了该方案。 You are making the request relative to the URL of the current page. 您正在相对于当前页面的URL发出请求。 This is almost certainly resulting in a 404 Not Found error. 几乎可以肯定会导致404 Not Found错误。

 xhr.onload = function() { if (xhr.status == 200) { document.getElementById("title").innerHTML = this.responseText; } } 

You have only an onload handler. 您只有一个onload处理程序。 There is no onerror handler, so no code is triggered then XHR receives the 404 error. 没有onerror处理程序,因此没有代码被触发,然后XHR收到404错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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