簡體   English   中英

AJAX全局變量? (JavaScript)

[英]AJAX global variable? (Javascript)

我有一個全局變量問題。 看這個:

function more_elems() {
var ret = [];

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
    {

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var JSONObject = JSON.parse(xmlhttp.responseText);
for (i=0;i<5;i++){
    ret[i] =
    {
    id: JSONObject[i].id,
    nombre: JSONObject[i].nombre,
    mensaje: JSONObject[i].mensaje,
    ult_m: JSONObject[i].ultima_modificacion
    };

}
alert(ret);
}
    }
xmlhttp.open("GET","somewesite.com",true);
xmlhttp.send();
return ret;

所以我試圖返回ret數組,但它返回未定義。 但是,如果我在xmlhttp.onreadystatechange = function()內發出警報,則確實會顯示帶有json對象的數組。 我不確定是什么問題= /。

提前致謝。

Ajax是異步的。 因此,當您在xmlhttp.send().之后立即調用時,將不會設置ret array xmlhttp.send().

一旦設置了ret array的值,就可以使用任何方法。 像下面這樣

xmlhttp.onreadystatechange=function()
    {

        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
             var JSONObject = JSON.parse(xmlhttp.responseText);
             for (i=0;i<5;i++){
            ret[i] ={
               id: JSONObject[i].id,
               nombre: JSONObject[i].nombre,
               mensaje: JSONObject[i].mensaje,
               ult_m: JSONObject[i].ultima_modificacion
            };

        }
        onAjaxSuccess(ret);
      }
    }

function onAjaxSuccess(arr){
    alert(arr);
}

暫無
暫無

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

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