Jquery .ajax()局部变量不能赋值给全局

时间:2013-04-03 19:04:11

标签: javascript jquery ajax

我有一个jquery ajax代码如下:

$(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()函数中获取值? 感谢任何人的帮助。

4 个答案:

答案 0 :(得分:6)

Ajax需要时间才能完成。函数执行时间不会太长。因此,当您在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
});

答案 1 :(得分:5)

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

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

我的建议是将其打破3个功能,这样会更有意义。你需要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
    }

})
相关问题