只有在ajax调用完成后才强制执行函数中的步骤?

时间:2014-03-11 16:50:41

标签: javascript jquery

在等待使用jQuery从异步调用返回值时,有没有办法暂停函数的其余部分?

2 个答案:

答案 0 :(得分:0)

您所谈论的是同步通话,不建议这样做,因为它会冻结用户界面。

相反,使用jQuery调用中提供的回调来执行其余的代码:

function DoSomeCall()
{
    $.post( "ajax/test.html", function( data ) {
      //Do your follow on code in here, in the callback.
    });

    //Don't do any code here that relies on the AJAX being finished first.
}

答案 1 :(得分:0)

实现此目标"暂停"行为,您希望将行为放在promise对象中。 https://api.jquery.com/jQuery.ajax/

$.ajax({
   url: "test.html",
   data: myData
}).success(function() {
  //put your code here this will only fire after it returns successfully
}).error(function() {
  //This will fire if there is an error 
});