jQuery的$。阿贾克斯(),传球成功数据转换成单独的函数 [英] jQuery $.ajax(), pass success data into separate function

查看:110
本文介绍了jQuery的$。阿贾克斯(),传球成功数据转换成单独的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery $。阿贾克斯()函数。我已经把它变成父函数,它传递一些值的AJAX功能。我想这样做,是有一个用户定义的回调函数,后者从阿贾克斯成功函数传递的数据参数。

下面是我在想会的工作,但它不是:

  testFunc =功能(STR,回调){
    //发送我们的PARAMS
    VAR数据='一些数据来发送;
    $阿贾克斯({
        键入:POST,
        网址:http://www.myurl.com,
        数据:数据,
        成功:回调
    });
}
 

然后,我希望能够调用该函数,并传递我的自定义函数,这样我可以从函数内部使用的成功功能的数据:

  testFunc(我的字符串数据',功能(数据){
    警报(数据);
});
 

我想这是一样的:

  testFunc =功能(STR,回调){
    //发送我们的PARAMS
    VAR数据='一些数据来发送;
    $阿贾克斯({
        键入:POST,
        网址:http://www.myurl.com,
        数据:数据,
        成功:功能(数据){
            警报(数据);
        }
    });
}
 

解决方案

正常工作:

 <脚本的src =/ jquery.js和>< / SCRIPT>
<脚本>
VAR回调=功能(数据,textStatus,XHR)
{
    警报(数据+\ t+ textStatus);
}

VAR测试=功能(STR,CB){
    VAR数据=输入值;
    $阿贾克斯({
        类型:'后',
        网址:http://www.mydomain.com/ajaxscript,
        数据:数据,
        成功:CB
    });
}
测试(你好,世界,回调);
< / SCRIPT>
 

I am using the jQuery $.ajax() function. I have put this into a parent function, which passes some values into the ajax function. What I would like to do, is have a user defined callback function, which gets the data param passed in from the ajax success function.

Here is what I was thinking would work, but it is not:

testFunc = function(str, callback) {
    // Send our params
    var data = 'some data to send';
    $.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: data,
        success: callback
    });
}

Then I want to be able to call that function, and pass in my custom function so that I can use the success functions data from inside that function:

testFunc('my string data', function(data){
    alert(data);
});

I am wanting this to be the same as:

testFunc = function(str, callback) {
    // Send our params
    var data = 'some data to send';
    $.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: data,
        success: function(data) {
            alert(data);
        }
    });
}

解决方案

Works fine for me:

<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
    alert(data + "\t" + textStatus);
}

var test = function(str, cb) {
    var data = 'Input values';
    $.ajax({
        type: 'post',
        url: 'http://www.mydomain.com/ajaxscript',
        data: data,
        success: cb
    });
}
test('Hello, world', callback);
</script>

这篇关于jQuery的$。阿贾克斯(),传球成功数据转换成单独的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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