简体   繁体   中英

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. (2.) log the responseText to the console.

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.

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

Please help me out.

You have your open() and send() methods inside your onreadystatechange() callback. 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);

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