2013-08-31 60 views
1

我使用AJAX請求從數據庫中獲取數值。 AJAX函數位於另一個函數內,該函數應返回AJAX請求的值。但是,因爲AJAX請求的返回值是xmlhttp.onreadystatechange函數內的局部變量,所以它不會更改return_count函數的「更高級別」temp_return。我不能讓「lower」函數返回值並將其賦值給一個變量,因爲它已經定義爲xmlhttp.onreadystatechange ...我怎樣才能改變這個,使得return_count函數將返回正確的值而不是42(預定義的出於測試目的)?從AJAX函數內部修改外部變量?

function return_count(ajax_userid,ajax_date,ajax_KT,ajax_KS) 
{ 
    var temp_return = 42; 
    xmlhttp.onreadystatechange = 
    function() 
    { 
     if(xmlhttp.readyState == 4 && xmlhttp.status == 200) 
     { 
      temp_return = xmlhttp.responseText; 
     } 
    } 
    xmlhttp.open("GET", "count.php?userid="+ajax_userid+"&date="+ajax_date+"&KT="+ajax_KT+"&KS="+ajax_KS, true); 
    xmlhttp.send(); 
    return temp_return; 
} 
+0

做出ajax請求[同步](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests),如果你不想阻塞頁面,你需要調用函數而不是返回。 –

+0

* AJAX中的* A *表示**異步**,您不能從ajax調用返回變量,您需要通過回調函數(通常作爲ajax的參數傳遞)來使用它「major」函數),它將只有一個參數(返回的數據,在本例中爲'xmlhttp.responseText'),並且將使用該參數進行調用。 –

+0

可能重複[如何從AJAX調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – adeneo

回答

1

你可以做到這一點的2種方式...

讓你AJAX(RECOMENDED)回調

創建異步回調繼續你的流量; d

function return_count(ajax_userid,ajax_date,ajax_KT,ajax_KS, callback) 
{ 
    var otherCallback; 
    var temp_return = 42; 
    xmlhttp.onreadystatechange = 
    function() 
    { 
     if(xmlhttp.readyState == 4 && xmlhttp.status == 200) 
     { 
      temp_return = xmlhttp.responseText; 
      if(typeof callback === "function") callback(temp_return); 
      if(typeof otherCallback === "function") otherCallback(temp_return); 
     } 
    } 
    xmlhttp.open("GET", "count.php?userid="+ajax_userid+"&date="+ajax_date+"&KT="+ajax_KT+"&KS="+ajax_KS, true); 
    xmlhttp.send(); 

    return { done: function (callback2){ 
      otherCallback = callback2; 

    } }; 
} 

你可以像下面這樣使用...

參數回調

return_count(userid, date, KT, KS, function (count) { 

    alert("returned " + count); 

});

或管回調

return_count(userid, date, KT, KS) 
    .done(function (count) { 

     alert("returned " + count); 

    }); 

作出同步AJAX

加入 「假」 來標誌異步...

function return_count(ajax_userid,ajax_date,ajax_KT,ajax_KS) 
{ 
    var temp_return = 42; 
    xmlhttp.onreadystatechange = 
    function() 
    { 
     if(xmlhttp.readyState == 4 && xmlhttp.status == 200) 
     { 
      temp_return = xmlhttp.responseText; 
     } 
    } 
    xmlhttp.open("GET", "count.php?userid="+ajax_userid+"&date="+ajax_date+"&KT="+ajax_KT+"&KS="+ajax_KS, false); 
    xmlhttp.send(); 
    return temp_return; 
} 

但這種方法鎖定您的UI是對UX不好。