简体   繁体   中英

Getting undefined in javascript when calling ajax

function get_request(url) {
  var request = new getXMLObject();
  request.onreadystatechange = function () {
    if (request.readyState == 4) {
      alert(request.responseText);
      var data = eval('(' + request.responseText + ')');
      alert(data);
      return data;
    }   
  }
  request.open("GET", url, true);
  //alert(document.getElementById('energy').innerHTML);
  request.send();
}

function loadjobs() {
  var url = "loadjobs.php?tab=1&id=1111";
  //var data=
  //alert(check());
  alert(get_request(url));
  //alert(data);
}

When im getting data in json format...i am gettin NULL in alert(get_request(url)); while im getting in alert(data);

Help me

This is because the request in asynchronous . The get_request(url) function does to return anything and hence the null ( although I think it should be undefined and not null ) .

The onreadystatechange function gets called later in the time , when the AJAX request has been completed and the data is returned from the server and hence the alert there works .

This is a misunderstanding of how AJAX works. Ajax is asynchronous . The onreadystatechange function will be called after loadjobs() . The "return path" you are specifying can never work. get_request() will never be able to return the fetched value.

You have two options. Either make the script synchronous - this can be done but is not recommended because it can freeze the browser.

Or, better, handle everything you need to do inside the onreadystatechange callback.

The problem is that Ajax requests work asynchronously . So you can't return the data right away. The way you should do it is to specify a callback function which will handle the response data.

function handleJSON( data ) {
  // ...
  // do whatever you want to do with the data
}

ajax( "url/file.php?param=value", handleJSON );

////////////////////////////////////////////////////////////////////////////////

function getXmlHttpObject() {
    var xmlHttp;
    try {
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

function ajax(url, onSuccess, onError) {
    var xmlHttp = getXmlHttpObject();
    xmlHttp.onreadystatechange = function () {
        if (this.readyState == 4) {
            // onError
            if (this.status != 200) {
                if (typeof onError == 'function') {
                    onError(this.responseText);
                }
            }
            // onSuccess
            else if (typeof onSuccess == 'function') {
                onSuccess(this.responseText);
            }
        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    return xmlHttp;
}​

Well, it's an asynchronous call. You will receive the data of request your after get_request has already returned. That means your request.onreadystatechange = function () will be executed long after alert(get_request(url)); is already finished. This means get_request will not be able to return any data from the AJAX call. That's what you have the request.onreadystatechange callback function for, to execute code at an undefined later time when you received the response.

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