最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - saving XMLHttpRequest.responseText in a variable - Stack Overflow

programmeradmin2浏览0评论

I'm writing a small script in JS to save the data using a php website like this:

function getPopulation(id) {
    var xhr_object = null;

    if(window.XMLHttpRequest) // Firefox
       xhr_object = new XMLHttpRequest();
    else if(window.ActiveXObject) // Internet Explorer
       xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
    else { // XMLHttpRequest non support? par le navigateur
       alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
       return;
    }

    var url = "http://localhost/inf347/td-svg/population.php?id=1";
    var res = 0;

    xhr_object.open("GET", url,true);
    xhr_object.send(null) ;
    xhr_object.onreadystatechange=function() {
        if (xhr_object.readyState==4) {
                //alert(xhr_object.responseText) ;
                res =   xhr_object.responseText ;
        }
    }
    alert(res);
    //return -1;
}

If I unment the line "//alert(xhr_object.responseText) ;" then the program prints the correct answer. But there is no way to save that value into a variable. Does anyone know how to get round it?

Thanks, Son

I'm writing a small script in JS to save the data using a php website like this:

function getPopulation(id) {
    var xhr_object = null;

    if(window.XMLHttpRequest) // Firefox
       xhr_object = new XMLHttpRequest();
    else if(window.ActiveXObject) // Internet Explorer
       xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
    else { // XMLHttpRequest non support? par le navigateur
       alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
       return;
    }

    var url = "http://localhost/inf347/td-svg/population.php?id=1";
    var res = 0;

    xhr_object.open("GET", url,true);
    xhr_object.send(null) ;
    xhr_object.onreadystatechange=function() {
        if (xhr_object.readyState==4) {
                //alert(xhr_object.responseText) ;
                res =   xhr_object.responseText ;
        }
    }
    alert(res);
    //return -1;
}

If I unment the line "//alert(xhr_object.responseText) ;" then the program prints the correct answer. But there is no way to save that value into a variable. Does anyone know how to get round it?

Thanks, Son

Share Improve this question asked Jun 5, 2011 at 15:58 user760759user760759 111 silver badge2 bronze badges 1
  • You need either an event handler function in which you pass the response to it if (readyState == 4), or save it to a global variable then call your event handler function. – Jared Farrish Commented Jun 5, 2011 at 16:02
Add a ment  | 

4 Answers 4

Reset to default 2

"alert(res);" will not work, because browser doesn't wait for AJAX call to plete, it executes the whole script. If you want to act on returned data, you need to add callback in your xhr_object.onreadystatechange function.

if (xhr_object.readyState==4) {
    //alert(xhr_object.responseText) ;
    res =   xhr_object.responseText ;

    act_on_response(res);
}

Somewhere else in the code:

function act_on_response(res)
{
    alert(res);
}

You must give a function name ... se below

 if (httpRequest.status == 200) 
                                       responseData(httpRequest);
                                     else
                                       window.status = httpRequest.statusText;      
                                    }
                                  }

  httpRequest.send(zallInOne); 
}

function responseData(dataFromServer) {
  var d = new Date(); 
  document.getElementById("sha1").style.color = "#ff6000";
  document.getElementById("sha1").value = dataFromServer.responseText;
   ...
  ...
 }

If you assign the response to a properly delcared global variable, or update the content of the document, it should work properly.

I guess the problem is with the last alert line.

xhr_object.onreadystatechange=function() {
    if (xhr_object.readyState==4) {
            //alert(xhr_object.responseText) ;
            res =   xhr_object.responseText ;
    }
}
alert(res); // THIS LINE

Note that onreadystatechange is a callback function, which means that this function will be called when the response is received. That is, the function is called asynchronously. So the application will continue to execute, and your alert can (will) be executed before the response is received. So you will get an alert which says '0'.

The alert is triggered before the responseText has arrived. You can either use a callback function, or move the alert up into the statechange function. This is because getPopulation starts the XMLHtpRequest, but in itself doesn't wait for pletion of that and executes everything that's in the function in one go. The readystatechange handler listens meanwhile for a trigger to act, but most of the time that trigger occurs after the calling function has executed.

// move alert up
if (xhr_object.readyState==4) {
  res =   xhr_object.responseText ;
  alert(res);
}
// use a callback
if (xhr_object.readyState==4) {
  myCallback(xhr_object.responseText);
}
function myCallback(res){
  alert(res);
}
发布评论

评论列表(0)

  1. 暂无评论