jquery - JQuery ajax调用的返回值

标签 jquery ajax return

我希望此函数返回 ajax 调用是否成功。我有什么办法可以做到这一点吗?我下面的代码不会执行此操作。

function myFunction(data) {
var result = false;
$.ajax({
    type: "POST",
        contentType: "application/json",
        dataType: "json",
        url: "url",
        data: data,
        error: function(data){
             result = false;
             return false;
        },
        success: function(data){
            result = true;
            return true;
        }
     });
     return result;
}

最佳答案

不幸的是,您无法将值返回给包装异步回调的函数。相反,来自 AJAX 请求的成功回调会将数据和控制权移交给另一个函数。我在下面演示了这个概念:

myFunction 的定义:

// I added a second parameter called "callback", which takes a function
 // as a first class object
function myFunction(data, callback) {
    var result = false;
    $.ajax({
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        url: "url",
        data: data,
        error: function(data){
            result = false;

            // invoke the callback function here
            if(callback != null)  {
                callback(result);
            }

            // this would return to the error handler, which does nothing
            //return false;
        },
        success: function(data){
            result = true;

            // invoke your callback function here
            if(callback != null) {
                callback(result);                
            }

            // this would actually return to the success handler, which does
              // nothing as it doesn't assign the value to anything
            // return true;
        }
     });

     // return result; // result would be false here still
}

回调函数定义:

// this is the definition for the function that takes the data from your
 // AJAX success handler
function processData(result) {

    // do stuff with the result here

}

调用您的 myFunction:

var data = { key: "value" }; /* some object you're passing in */

// pass in both the data as well as the processData function object
 // in JavaScript, functions can be passed into parameters as arguments!
myFunction(data, processData);

关于jquery - JQuery ajax调用的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10768991/

相关文章:

javascript - 在 JS 中返回 parseInt 给我未定义

return - 订单与SBCL中的返回有关

javascript - 如何使用 CSS 或 jQuery 旋转元素并正确定位它

php - 获取提交数据的 id 返回 NaN

发出ajax请求时禁止AJAX 403

javascript - Jquery 限制用户每分钟上传 5 个帖子

Java : Method return Issue

javascript - jQuery Validate Plugin - 触发单个字段的验证

javascript - 如何按字母顺序对 select2(jQuery 插件)选项进行排序?

c# - 配置 web.config 以允许来自远程源的 js