-1

我需要应用程序等到第一个请求完成。情景是,

if (str != "") {
  if (str.match(",")) {
        var poolSequencedStatus = $.get("Request1.do"), function(response){
             //alert("Req1")
        }
  }

  $.get("Request2.do"), function(response){
     //alert("Req2")
  }
}

如果字符串包含字符“,”,则只有在完成 Request1 后才应调用 Request2。

4

4 回答 4

0

您可以利用 Promise 并将其包装在$.when($.get("Request1.do")).then(function(){});

http://api.jquery.com/jquery.when/

于 2014-05-26T05:45:47.023 回答
0

创建第二个请求的函数:

function GetRequest()
{

 $.get("Request2.do"), function(response){
     //alert("Req2")
  }

}

并调用第一个成功:

if (str != "") {
  if (str.match(",")) {
        var poolSequencedStatus = $.get("Request1.do"), function(response){
             GetRequest();
        }
  }
于 2014-05-26T05:46:42.163 回答
0
if (str != "") {
  if (str.match(",")) {
        var poolSequencedStatus = $.get("Request1.do"), function(response){
             //alert("Req1");
           $.get("Request2.do"), function(response){
     //alert("Req2")
           }
        }
  }


}
于 2014-05-26T05:47:02.617 回答
0

默认情况下,Jquery 在同步模式下工作。

检查 $.ajax 设置的 async:false 值。

否则,您可以在最新的 jQuery 中使用 $.when() 的好处。

    // Using the $.when() method, we can create an object that behaves similarly
// to Deferred objects, but for COMBINATIONS of Deferred objects.
//
// The $.when() method creates a Deferred object that is resolved or rejected
// when all the Deferred objects passed into it are resolved or rejected.
var getPromise = function(name) {
  var dfd = $.Deferred();
  var num = Math.floor(Math.random() * 1000);
  setTimeout(function() { dfd.resolve(name + ": " + num); }, num);
  return dfd.promise();
};

var list = $("<ul/>").appendTo($("#target").empty());
var printLine = function(str) {
  $("<li class=well/>").html(str).appendTo(list);
};

// Each of these Promises will individually print when resolved.
var promiseA = getPromise("A").done(printLine);
var promiseB = getPromise("B").done(printLine);
var promiseC = getPromise("C").done(printLine);

// And this code will execute once all Promises have resolved.
$.when(promiseA, promiseB, promiseC).then(function(numA, numB, numC) {
  printLine(numA + ", " + numB + ", " + numC);
});
于 2014-05-26T05:48:07.060 回答