jQuery同步问题

时间:2011-01-20 11:00:05

标签: jquery ajax asynchronous

我和json有两个ajax调用。 第一个帮助我获得globalVar值。 第二个获取此值,将其传递给远程URL中的参数,然后返回结果。

var globalVar = "";

var firstRemoteUrl = "http://example.com/some/json";
        $.ajax({
            type: "GET",
            url: firstRemoteUrl ,
            dataType: 'jsonp',
            success: function (data) {
                globalVar = data;
            }
        });


var secondRemoteUrl = "http://example.com/another/json?var = " + globalVar;
        $.ajax({
            type: "GET",
            url: secondRemoteUrl ,
            dataType: 'jsonp',
            success: function (data) {
                alert(data);
            }
        });

这种调用的问题是第二个ajax调用不会等到第一个调用完成后再调用。 因此,有时候,globalVar是空的。因此,第二次通话将无法正常结束。

我尝试使用async set ti false但是,正如jquery文档中所示,jsonp数据类型忽略了同步调用。

这个问题是否存在问题?

谢谢,

问候。

2 个答案:

答案 0 :(得分:1)

您可以将第二个调用放在第一个调用的回调中。这有点乱,但应该完成工作。像这样:

$.ajax({
 type: "GET",
 url: "http://example.com/some/json",
 dataType: 'jsonp',
 success: function(data) {
  $.ajax({
   type: "GET",
   url: "http://example.com/another/json?var = " + data,
   dataType: 'jsonp',
   success: function(result) {
    alert(result);
   }
  });
 }
});

答案 1 :(得分:1)

将第二个ajax调用放在第一个ajax调用的成功回调函数中。

var firstRemoteUrl = "http://example.com/some/json";
    $.ajax({
        type: "GET",
        url: firstRemoteUrl ,
        dataType: 'jsonp',
        success: function (data) {
            globalVar = data;
            secondRemoteUrl = "http://example.com/another/json?var = " + globalVar;
                             $.ajax({
                                     type: "GET",
                                     url: secondRemoteUrl ,
                                      dataType: 'jsonp',
                                      success: function (data) {
                                                  alert(data);
                                                }
                                      });
                            }
          });