2013-04-03 74 views
6

我有一个jquery Ajax代码如下:jQuery的阿贾克斯()的局部变量不能分配给全球

$(document).ready(function() { 
    var global_arr = new Array(); 
    $.ajax({ 
    url: 'result.php', 
    type: 'post', 
    dataType: 'json', 
    success: function(data) { 
     $.each(data, function(key, value) { 
      global_arr.push(value.name); 
     }); 
     alert(global_arr); //get correct value, works fine 
    } 
    }); //end of ajax function 
    alert(global_arr); //get null, it doesn't work properly 
}); 

通知行提醒global_arr,为什么我不能获得价值$出来的.ajax()函数? 谢谢大家对此的帮助。

+0

我们最喜欢的问题,异步调用! – epascarello 2013-04-03 19:18:01

回答

6

阿贾克斯需要时间来完成。功能执行不会花费太多时间。因此,当您在ajax请求之外发现警报时,ajax请求仍在使用时间来完成(无论是在传输中还是在服务器端操作中)。

您可以随时等待ajax方法完成。

$(document).ready(function() { 

var global_arr = new Array(); 
var complete = false;//flag to wait for ajax completion 
$.ajax({ 
    url: 'result.php', 
    type: 'post', 
    dataType: 'json', 
    success: function(data) { 
    $.each(data, function(key, value) { 
     global_arr.push(value.name); 
    }); 
    alert(global_arr); //get correct value, works fine 
    complete = true;//mark ajax as complete 
    } 
}); //end of ajax function 

(function runOnComplete(){ 
    if(complete){//run when ajax completes and flag is true 
    alert(global_arr); 
    }else{ 
    setTimeout(runOnComplete,25);//when ajax is not complete then loop 
    } 
})() 
}); 

但是,最常见的方法是使用回调。这里

$(document).ready(function() { 

function runOnComplete(){//code executes once ajax request is successful 
    alert(global_arr); 
} 
var global_arr = new Array(); 
$.ajax({ 
    url: 'result.php', 
    type: 'post', 
    dataType: 'json', 
    success: function(data) { 
    $.each(data, function(key, value) { 
    global_arr.push(value.name); 
    }); 
    alert(global_arr); //get correct value, works fine 
    runOnComplete();//callback 
    } 
}); //end of ajax function 
}); 
+0

干得好,谢谢! – user2241859 2013-04-04 13:04:09

+0

有趣。从异步特别是你的第一种方法中学到了很多东西。也就是说,你基本上等待ajax方法的完成。谢谢。 – racl101 2014-02-18 17:21:59

5

Ajax是异步的。当JS引擎到达无效的alert()行时,AJAX调用还没有机会从服务器获得响应并设置该变量。

这就是内部alert()工作的原因。当响应从服务器进入时它会被执行。

0

,这是因为alert(global_arr); //get null, it doesn't work properly$.ajax运行前已经完成

0

我的建议是在打破这种缩小到3个funcitons所以它将使更多的意义。你需要ajax,handelRequest,onComplete。 您可能还想为ajax函数添加错误处理程序,如果失败,可以在用户锁定脚本的情况下执行此操作。

$(document).ready(function() { 

    var global_arr = new Array(); 

    $.ajax({ 
     url: 'result.php', 
     type: 'post', 
     dataType: 'json', 
     success: handelRequest(data), 
     error: handleError    
    }); 

    function handelRequest(data) {   
     $.each(data, function (key, value) { 
      global_arr.push(value.name); 
     }); 
     onComplete(global_arr); //get correct value, works fine 
    } 

    function onComplete(global_arr){ 
     // then here you can do what ever you 
     // you would like with the array 
     alert(global_arr); 
    } 

    function handleError(){ 
     // gracefully fail 
    } 

}) 
+0

非常感谢! – user2241859 2013-04-04 13:04:27