Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在从函数返回之前等待AJAX完成?_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript 在从函数返回之前等待AJAX完成?

Javascript 在从函数返回之前等待AJAX完成?,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有以下几点 function doAjax() { var result = false; $.ajax(url, data) .done(function(){ // Do a bunch // of computation // blah blah blah result = true; }).fail(function(){ result = false; }); return re

我有以下几点

function doAjax()
{
  var result = false;
  $.ajax(url, data)
    .done(function(){
       // Do a bunch
       // of computation
       // blah blah blah
       result = true;
    }).fail(function(){
       result = false;
    });
  return result;
}

function doSomething()
{
  if ( doAjax() == true )
    console.log('success');
  else
    console.log('failed');
}

function doSomethingElse()
{
  if ( doAjax() == true )
    console.log('success');
  else
    console.log('failed');
}
我有一个函数,它运行一些ajax,然后返回true或false,这取决于ajax是否成功。我在代码中的多个地方调用了这个ajax函数

因为函数在ajax完成之前结束,所以它总是返回false。我如何避免这种情况

我读到一些建议我在函数中执行
返回$.ajax()
,然后将
.done()
.fail()
函数移动到我的
doSomething()
doSomethingElse()
函数。然而,在我的
.done()
方法中,我进行了大量计算。很多代码。所以问题是,如果我将
.done()
函数移动到其他函数,我会复制一堆代码


我如何避免这种情况?只需将计算包装到它自己的函数中,并在必要时调用它?

永远不要使用Ajax返回,它永远不会工作。使用Ajax
success
函数:

$.ajax({
   url: 'http://localhost',
   success: function(data){
        var doStuff = true;
        var responseFromServer = data;
        callSomeFooFunction();
        //return will not work!
   }
})

当Ajax处于异步模式时,它将无法工作(
async:false
)。尝试以以下方式对代码进行结构化:

function doABuncnchOfComputation(args){ // no duplicates here
    // Do a bunch
    // of computation
    // blah blah blah
}

// doSomething:
$.ajax(url, data)
    .done(function(){
       doABuncnchOfComputation(...); // call with proper arguments, possibly received from server
       console.log('doSomething succeeded');
    }).fail(function(){
       console.log('doSomething failed');
    });

// doSomethingElse:
$.ajax(url, data)
    .done(function(){
       doABuncnchOfComputation(...); // call with proper arguments, possibly received from server
       console.log('doSomethingElse succeeded');
    }).fail(function(){
       console.log('doSomethingElse failed');
    });
因此,您的主计算块
doabuncnchofcompution()
将保持不变,并可用于每个异步操作


当网络传输处于活动状态时,将Ajax模式设置为synchronous将阻止浏览器执行任何操作。由于可能的网络不稳定,它可能会导致“糟糕”的用户体验—浏览器可能挂起,页面将处于非活动状态且无响应状态,而Ajax将发送/接收或等待数据。这是非常不可靠和令人沮丧的。

从技术上讲,您可以使您的ajax
同步化
如下:

 $.ajax({url:myUrl, data:myData, async: false})
但这并不推荐(仅适用于真正具体的事情)。
否则,只需使用
回调
,如本例所示:

var menuId = $( "ul.nav" ).first().attr( "id" );    
var request = $.ajax({   
  url: "script.php",    
  type: "POST",    
  data: { id : menuId },   
  dataType: "html"    
});

request.done(function( msg ) {    
  $( "#log" ).html( msg );   
});

request.fail(function( jqXHR, textStatus ) {    
  alert( "Request failed: " + textStatus );    
});

阅读更多。

重新构造代码,使用回调而不是返回,如下所示

function doAjax(callback)
{
  $.ajax(url, data)
    .done(function(){
       // Do a bunch
       // of computation
       // blah blah blah
       callback(true);
    }).fail(function(){
       callback(false);
    });
}

function doSomething()
{
  doAjax(function(result){
    if (result == true )
       console.log('success');
    else
       console.log('failed');
  });
}

function doSomethingElse()
{
  doAjax(function(result){
    if (result == true )
       console.log('success');
    else
       console.log('failed');
  });
}

result
将始终
返回false
,这是正常的,因为ajax请求是异步的。因此,您必须使用
.done()
或回调函数。是的:为了避免代码重复(如果你遇到了这个问题),设置必要的代码来分离函数。我知道这并不能解决我的问题,但是根据,
.done()
替换了不推荐的
.success()
函数。@Jakobud无论如何,你的函数
返回
(不是在ajax中)将在ajax完成之前执行,并且ajax中的
return
将不返回任何位置,请使用回调函数show处理url是否是动态的?@reggie-听起来您有一个。。。