简体   繁体   English

Ajax(XMLHttpRequest)请求的responseText未定义

[英]responseText of Ajax (XMLHttpRequest) request is undefined

I have been trying my hands on a simple console app which will do two things. 我一直在尝试一个简单的控制台应用程序,它将做两件事。 (1.) It will make an asynchronous Ajax request. (1.)它将发出异步Ajax请求。 (2.) log the responseText to the console. (2.)将responseText记录到控制台。

To go about this,i made my ajax request to openweathermap.org and tried to parse the responseText to JSON and finally log it to the console. 为此,我向openweathermap.org提出了ajax请求,并尝试将responseText解析为JSON,最后将其记录到控制台。

Please find below my code to achieve this 请在下面找到我的代码以实现此目的

var data ;
var url = "http://api.openweathermap.org/data/2.5/weather?id=7535661&APPID=56104080d6cb412468dad1627cb27da6";

var myRequest;

function sendRequest(url){
    myRequest = new XMLHttpRequest();
    myRequest.onreadystatechange= function(){
    if(myRequest.readyState == 4 && myRequest.status== 200){
       data= JSON.parse(myRequest.responseText);

    }
   myRequest.open("GET", url, true );
   myRequest.send();
    }
   console.log(data);
   }

sendRequest(url);

Each time i try running this, it is always returing "undefined". 每次我尝试运行此命令时,它总是重播“ undefined”。

Please help me out. 请帮帮我。

You have your open() and send() methods inside your onreadystatechange() callback. 您在onreadystatechange()回调中具有open()send()方法。 So, you're never opening the connection, unless the request completes. 因此,除非请求完成,否则您永远不会打开连接。 Try this: 尝试这个:

var data;
var url = "http://api.openweathermap.org/data/2.5/weather?id=7535661&APPID=56104080d6cb412468dad1627cb27da6";

var myRequest;

function sendRequest(url) {
  myRequest = new XMLHttpRequest();
  myRequest.onreadystatechange = function() {
    if (myRequest.readyState == 4 && myRequest.status == 200) {
      data = JSON.parse(myRequest.responseText);
      console.log(data);
    }
  }
  myRequest.open("GET", url, true);
  myRequest.send();
}

sendRequest(url);

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

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