Javascript AJAX请求成功时如何返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6854542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:28:54  来源:igfitidea点击:

How to return value when AJAX request is succeeded

javascriptjqueryajaxasynchronousreturn-value

提问by Artur Keyan

   function ajaxRefresh(actionUrl) {
        $.ajax({
        url: actionUrl,
        success: function() {
             return true;
        }});
        return false;
    }

The function anyway returns falseeven when a request is succeeded, becouse the request is asynchronous. How I can return truewhen request is succeeded?

false即使请求成功,该函数也会返回,因为请求是异步的。true请求成功后如何返回?

回答by Pavel Surmenok

You should set parameter asyncto false. Try this code:

您应该将参数设置asyncfalse. 试试这个代码:

function ajaxRefresh(actionUrl) {
    var succeed = false;

    $.ajax({
    async: false,
    url: actionUrl,
    success: function() {
         succeed = true;
    }});

    return succeed;
}

回答by Arxisos

You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.

在 ajax 请求尚未完成之前,您无法返回“true”,因为正如您提到的那样,它是异步的。所以这个函数在ajax请求完成之前就离开了。

Solution 1

解决方案1

function ajaxRefresh(actionUrl, successCallback) {
    $.ajax({
       url: actionUrl,
       success: successcallback
    });
}

But there's a workaround: Just add a callback parameter to the function. This function will be executed when the request has finished.

但是有一个解决方法:只需向函数添加一个回调参数。这个函数会在请求完成后执行。

Solution 2

解决方案2

You can return a jquery deferred.

您可以返回延迟的 jquery。

function ajaxRefresh(actionUrl, successCallback) {
    return $.ajax({
       url: actionUrl
    });
}

Now you can use the function like:

现在您可以使用如下函数:

function otherFunction()
{
     ajaxRefresh().success(function() {
        //The ajax refresh succeeded!
     }).error(function() {
        //There was an error!
     });
}

For more information about jquery deferreds look at http://www.erichynds.com/jquery/using-deferreds-in-jquery/.

有关 jquery 延迟的更多信息,查看http://www.erichynds.com/jquery/using-deferreds-in-jquery/

回答by nnnnnn

You can refactor your code a little bit so that your success callback triggers the next operation that depends on the true/false result. For example, if you currently have something like:

您可以稍微重构您的代码,以便您的成功回调触发下一个取决于真/假结果的操作。例如,如果您目前有以下内容:

function main() {
  // some code

  if (ajaxRefresh(url)) {
    // do something
  }
}

You would change that to something like:

您可以将其更改为:

function main() {
  // some code

  ajaxRefresh(url);
}

function doSomething(successFlag) {
  if (successFlag) {
    // do something
  }
}

function ajaxRefresh(actionUrl) {
  $.ajax({
         url: actionUrl,
         success: function() {
           doSomething(true); // or false as appropriate
         }});
}

You could also put the iftest into the ajax callback function instead of in the doSomething()function. Up to you.

您也可以将if测试放入 ajax 回调函数而不是doSomething()函数中。由你决定。

Or you can make a synchronous request, and figure out the ajaxRefresh()function's return value after the request is done. I would not recommend that for most purposes.

或者你可以做一个同步请求,并ajaxRefresh()在请求完成后找出函数的返回值。对于大多数目的,我不建议这样做。

回答by ttemple

I am a relatively newbie at this, but here is a suggested work around I came up with which eliminates the need to set asynchto false or anything like that. Just set a hidden field value with the result of the ajax call, and instead of checking return value, check the value of the hidden field for true/false (or whatever you want to put in it).

我在这方面是一个相对新手,但这里有一个我提出的建议工作,它消除了设置asynch为 false 或类似内容的需要。只需使用 ajax 调用的结果设置一个隐藏字段值,而不是检查返回值,而是检查隐藏字段的值是否为真/假(或您想放入的任何内容)。

Example: function doSomething() {

示例:函数 doSomething() {

    $.ajax({
        ...blah blah 
        },
        success: function(results) {
            if(results === 'true') {
                $('#hidField').val('true');
            }
            else {
                $('#hidField').val('false');
            }
        }
    });

Then somewhere else where it's required, this doSomethingfunction is called, and instead of checking the result of the ajax call, look for the hidden field value:

然后在其他需要它的地方,doSomething调用此函数,而不是检查 ajax 调用的结果,而是查找隐藏字段值:

doSomething();

var theResult = $('#hidField').val();

if (theResult == 'true') {

...do whatever...

}

回答by Naga Harish M

Use call back functions

使用回调函数

Callback Function Queues:-

回调函数队列:-

The beforeSend, error, dataFilter, success and complete options all accept callback functions that are invoked at the appropriate times.

beforeSend、error、dataFilter、success 和 complete 选项都接受在适当时间调用的回调函数。

so, here

所以在这里

function ajaxRefresh(actionUrl) {
        $.ajax({
        url: actionUrl,
        success: function() {
             return true;
        }
        error:function(){
             return false;
        }
     });        
    }

You can get more details here

您可以在此处获得更多详细信息

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

回答by Ashley John

function ajaxRefresh(actionUrl) {   
    bool isSucesss=false;
    $.ajax({       
        url: actionUrl,        
        success: function() {   
            isSucesss=true;     
        },
        error:function() {   
            isSucesss= false;     
        }
    });     
    return isSucesss;
}