2013-03-23 89 views
0

我想在Javascript中進行AJAX調用以獲取兩個值。然後我想全局使用這些值做一些計算,然後打印出結果。以下是我的代碼。Ajax請求在調用後不設置全局變量

// 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. 所以我的第一個問題是,爲什麼總價值= 1個+值2仍然是0。我已經讓他們的全局變量,然後更新內部makeRequest的()的值1和值2,但似乎沒有影響價值。我該怎麼做才能更新value1和value2,以便在這些函數之外使用它們。

  2. 基本上我從在線教程複製ajax請求代碼。有一件事我不明白在這裏。當我調用MakeRequest()函數時,它調用AjaxRequest(「values.xml」,AjaxResponse,「get」);但是,AjaxReponse(req)在這裏需要一個參數「req」。但AjaxRequest(「values.xml」,AjaxResponse,「get」)中的AjaxResponse沒有放置參數。它仍然有效。這是爲什麼?我真的明白這個部分。

+1

AJAX中的A代表「異步」。調用'MakeRequest()'不會阻塞。 – Blender 2013-03-23 00:18:12

回答

4

因爲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 

total = value1 + value2應計算您的AJAX請求成功返回,如果你想value1value2取決於AJAX請求的結果。