简体   繁体   中英

Ajax request does not set global variable after call

I am trying to make a AJAX call in Javascript to get two values. Then I want to use these values globally to do some calculation and then print the result out. The following is my codes.

   // my calculation functions will go here

   var value1 = 0;
   var value2 = 0;
   MakeRequest(); //after makeRequest() value1 and value2 should be 10 and 20 respectively.
   var total = value1 + value2;
   console.log(total); // this is still zero. because value1 and value2 are still 0.


//request AJAX
    function createXMLHTTPObject(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
            // IE 7+, Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
            return ajaxRequest;
        } catch (e){
            // Internet Explorer
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                return ajaxRequest;
            } catch (e) {
                try{
                    // Internet Explorer 5, 6
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    return ajaxRequest;
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }
    }

    // Create a function that will receive data sent from the server
    function AjaxRequest(url,callback,method){
        var req = createXMLHTTPObject();
        req.onreadystatechange= function(){
                if(req.readyState != 4) return;
                if(req.status != 200) return;
                callback(req);
        }
        req.open(method,url,true);
        req.send(null);
    }

    function AjaxResponse(req){
        var respXML=req.responseXML;
        if(!respXML) return;
        value1=respXML.getElementsByTagName("value1")[0].childNodes[0].nodeValue;
        value2= respXML.getElementsByTagName("value2")[0].childNodes[0].nodeValue;
        console.log("the value1 is "+ value1);  //successfully print the values
        console.log("the value2 is "+ value2);
    } 

    function MakeRequest(){
         AjaxRequest("values.xml",AjaxResponse,"get");
    }
  1. So my first question is that why total = value 1 + value2 are still 0. I have made them global variables and then updated value1 and value2 inside of makeRequest(), but it seems not affect the value. What could I do so that I can update value1 and value2 in order to use them outside of those functions.

  2. Basically I copy the ajax request codes from a tutorial online. There is one thing I dont understand here. When I call MakeRequest() function, it calls AjaxRequest("values.xml",AjaxResponse,"get"); However, AjaxReponse(req) needs a parameter "req" here. But AjaxResponse inside of AjaxRequest("values.xml",AjaxResponse,"get") did not put a parameter. it still works. Why is that? I do really understand this part.

Because AJAX calls are asynchronous which means your code runs like this in realtime:

var value1 = 0;
var value2 = 0;
MakeRequest();           // AJAX REQUEST is made, that will happen on its on timeline
var total = value1 + value2;
console.log(total);     // still will be 0 at this point, since AJAX response has not returned


// MakeRequest will fire AJAX request and WHEN THE REQUEST IS SUCCESSFUL, it can modify value1 and value2, then calculate total  

The total = value1 + value2 should be calculated after your AJAX request returns successfully, if you want value1 and value2 to be dependent on the AJAX request's result.

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