簡體   English   中英

從變量中的Ajax請求獲取價值

[英]Getting value from Ajax request in variable

我有這個功能。

function ajaxtakesource4(callback){
    var ajaxRequest;  // The variable that makes Ajax possible!
    try{
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                alert("Your browser broke!");
                return false;
            }
        }
    }   
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange =function(){
        if(ajaxRequest.readyState == 4 &&ajaxRequest.status==200){
            var sourcetest = ajaxRequest.responseText;  
            callback(sourcetest);
        }
    }
    ajaxRequest.open("POST", "takesource4.php", true);
    ajaxRequest.send(null); 
}

也:

var somous4;
function run() {
    ajaxtakesource4(function(sourcetest){   
        somous4=sourcetest;
    });
    alert(somous4);
}

在這里,我將上面的函數稱為:

<div id="run">
  <button id="button_run" class="button" onclick="run()">Run</button>
</div>

當我單擊該按鈕時,它應該警報來自Ajax請求的響應,但看起來是在警報一個虛假的值( undefined ),如以下行所示:

alert(somous4);

異步代碼本質上是並發執行的。 因此,您的alert語句可能回調執行之前執行(回調僅在從服務器接收回數據之后才會執行)。 alert放在回調中,它將顯示返回的值,即

var somous4;
function run() {
    ajaxtakesource4(function(sourcetest){   
        somous4=sourcetest;
        alert(somous4);
    });
}

編輯:基於OP的注釋,而不是考慮返回值,請執行以下操作:

function foo(soumous4) { // use somous4 for whatever you want... }

// Call this function foo inside the callback.
ajaxtakesource4(function(sourcetest){   
        somous4=sourcetest;
        foo(somous4);
    });

我建議您按以下方式更改run函數中的回調:

var somous4;
function run() {
    ajaxtakesource4(function(sourcetest){   
        somous4=sourcetest;
        alert(somous4);
    });
}

您正在警告somous4然后再通過請求回調對其進行更改 在這種情況下,命令塊比請求回調 執行。

服務器端語言(如PHP) 自動完成工作,因此您無需在其中使用事件 請求未完成時它會休眠。 那是因為命令塊打開了事件回調

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM