返回AJAX调用数据的JavaScript函数 [英] JavaScript function that returns AJAX call data

查看:138
本文介绍了返回AJAX调用数据的JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个JavaScript函数返回一个jQuery AJAX调用的值。我想是这样的。

 函数checkUserIdExists(用户ID){
    返回$阿贾克斯({
        网址:theurl,
        键入:GET,
        缓存:假的,
        数据: {
           用户ID:用户ID
        },
        成功:功能(数据){
            返回的数据;
        }
    });
}
 

我知道我可以通过设置异步为false做到这一点,但我宁可不要。

解决方案

使用jQuery 1.5,可以使用全新的 $。递延> <$ C $ 功能,这意味着正是这一点。

  //指定处理程序,立即发出请求后,
//并记住jqxhr对象申请
VAR jqxhr = $阿贾克斯(网址:{url:使用example.php})
    .success(函数(){警报(成功);})
    .error(函数(){警报(错误);})
    .complete(函数(){警报(完成);});

//这里执行其他工作...

//为请求设置另一完成以上功能
jqxhr.complete(函数(){警报(第二次完成);});
 

来源

I would like to create a JavaScript function which returns the value of a jQuery AJAX call. I would like something like this.

function checkUserIdExists(userid){
    return $.ajax({
        url: 'theurl',
        type: 'GET',
        cache: false,
        data: {
           userid: userid
        },
        success: function(data){
            return data;
        }
    });
}

I know I can do this by setting async to false but I would rather not.

解决方案

With jQuery 1.5, you can use the brand-new $.Deferred feature, which is meant for exactly this.

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax({ url: "example.php" })
    .success(function() { alert("success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });

Source

这篇关于返回AJAX调用数据的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆