简体   繁体   English

调用后Ajax请求未设置全局变量

[英]Ajax request does not set global variable after call

I am trying to make a AJAX call in Javascript to get two values. 我正在尝试用Javascript进行AJAX调用以获取两个值。 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. 因此,我的第一个问题是,为什么total =值1 + value2仍然为0。我使它们成为全局变量,然后在makeRequest()中更新了value1和value2,但似乎不影响该值。 What could I do so that I can update value1 and value2 in order to use them outside of those functions. 我该怎么做才能更新value1和value2以便在这些功能之外使用它们。

  2. Basically I copy the ajax request codes from a tutorial online. 基本上,我从在线教程中复制ajax请求代码。 There is one thing I dont understand here. 我在这里不了解一件事。 When I call MakeRequest() function, it calls AjaxRequest("values.xml",AjaxResponse,"get"); 当我调用MakeRequest()函数时,它将调用AjaxRequest(“ values.xml”,AjaxResponse,“ get”); However, AjaxReponse(req) needs a parameter "req" here. 但是,AjaxReponse(req)在这里需要参数“ req”。 But AjaxResponse inside of AjaxRequest("values.xml",AjaxResponse,"get") did not put a parameter. 但是AjaxRequest(“ values.xml”,AjaxResponse,“ get”)内的AjaxResponse没有放置参数。 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: 因为AJAX调用是异步的 ,这意味着您的代码可以实时运行:

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. 如果您希望value1value2依赖于AJAX请求的结果,则应 AJAX请求成功返回计算total = value1 + value2

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

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