嗨,我的脚本中有2个Ajax调用,我需要它们运行asnyc以节省时间,但是我需要第二个才能等待第一个完成。
$.ajax({ type: "POST", url: "getText.asmx/ws_getText", data: parO1, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert(msg.d.data); } , error: function () { chyba("chyba v požadavku", "df"); } }); if (parO2.length > 0) { $.ajax({ type: "POST", url: "getText.asmx/ws_getText", data: parO2, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { /*WAIT UNTIL THE FIRST CALL IS FINISHED AND THAN DO SOMETHING*/ } , error: function () { chyba("chyba v požadavku", "df"); } });
有什么想法吗?谢谢
如果使用jQuery 1.5+,则可以使用jQuery jQuery.when()完成。诸如此类的东西(缩短了ajax的简洁性,只需像上面那样传递对象)
jQuery.when()
$.when($.ajax("getText.asmx/ws_getText"), $.ajax("getText.asmx/ws_getText")).done(function(a1, a2){ // a1 and a2 are arguments resolved for the // first and second ajax requests, respectively var jqXHR = a1[2]; // arguments are [ "success", statusText, jqXHR ] });
您不知道它们将以什么顺序返回,因此,如果您手动滚动此请求,则需要检查另一个请求的状态并等待它返回。