$.getJSON异步请求和同步请求

先看一段代码:

for(var j=0;j<24;j++){
     (jQuery).getJSON('log_analyze.php',{r:Math.random(),logid:logid,op:2,j:j},function(data){
          if(data.success_agent){
              var width=j*10;
               $("#up_time_loading").empty().append("<div style=\"width:"+width+"px;height:10px;border:1px solid #333;background-color:#333\"></div>");
              }
                   })
               }

这段代码的意思是:请求log_analyze.php,每次请求成功后就把J加1,然后再去请求。

打开firebug,可以看到这24条数据是异步执行,所以我log_analyze.php获取到得数据很混乱,没有规律,怎么解决呢?

在执行之前加$.ajaxSettings.async = false;    (同步执行)

$.ajaxSettings.async = false; 
for(var j=0;j<24;j++){ (jQuery).getJSON('log_analyze.php',{r:Math.random(),logid:logid,op:2,j:j},function(data){ if(data.success_agent){ var width=j*10; $("#up_time_loading").empty().append("<div style=\"width:"+width+"px;height:10px;border:1px solid #333;background-color:#333\"></div>");               }  }) }

在for循环之前加一个$.ajaxSettings.async = false;    表示同步执行,这样他就会安装顺序执行了。

下面的是从网上摘过来的:

同时执行多个$.getJSON() 数据混乱的问题的解决

在执行之前加$.ajaxSettings.async = false;    (同步执行)
执行你的代码之后及时恢复为$.ajaxSettings.async = true; (异步执行)
不然影响别的地方的需要异步执行的代码。

example:

$.ajaxSettings.async = false;

$.getJSON(url, data, function(data){ });

$.getJSON(url, data, function(data){ });

$.getJSON(url, data, function(data){ });

......

$.ajaxSettings.async = true;

 

posted @ 2012-11-19 17:43  KoMiles  阅读(67690)  评论(0编辑  收藏  举报