jQuery $.ajax()将成功数据传递到单独的函数中。

时间:2022-12-08 20:20:58

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.

我使用的是jQuery $.ajax()函数。我将其放入父函数中,它将一些值传递到ajax函数中。我想要做的是,有一个用户定义的回调函数,它从ajax success函数中获取数据param。

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);
        }
    });
}

6 个解决方案

#1


29  

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>

#2


21  

You can use this keyword to access custom data, passed to $.ajax() function:

您可以使用此关键字来访问自定义数据,传递给$.ajax()函数:

    $.ajax({
        // ... // --> put ajax configuration parameters here
        yourCustomData: {param1: 'any value', time: '1h24'},  // put your custom key/value pair here
        success: successHandler
    });

    function successHandler(data, textStatus, jqXHR) {
        alert(this.yourCustomData.param1);  // shows "any value"
        console.log(this.yourCustomData.time);
    }

#3


2  

In the first code block, you're never using the str parameter. Did you mean to say the following?

在第一个代码块中,您永远不会使用str参数。你的意思是说下面的话吗?

testFunc = function(str, callback) {
    $.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: str,
        success: callback
    });
}

#4


2  

this is how I do it

我就是这么做的。

function run_ajax(obj) {
    $.ajax({
        type:"POST",
        url: prefix,
        data: obj.pdata,
        dataType: 'json',
        error: function(data) {
            //do error stuff
        },
        success: function(data) {

            if(obj.func){
                obj.func(data); 
            }

        }
    });
}

alert_func(data){
    //do what you want with data
}

var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);

#5


1  

I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)

我相信您的问题是您正在传递testFunct一个字符串,而不是一个函数对象,(这可能吗?)

#6


1  

Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:

虽然我不是百分之百确定你想要什么(也许我的大脑今天很迟钝),这里有一个类似于你所描述的用法的例子:

function GetProcedureById(procedureId)
{
    var includeMaster = true;
    pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: pString,
        datatype: "json",
        dataFilter: function(data)
        {
            var msg;
            if (typeof (JSON) !== 'undefined' &&
                    typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');
            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
        success: function(msg)
        {
            LoadProcedure(msg);
        },
        failure: function(msg)
        {
            // $("#sometextplace").text("Procedure did not load");
        }
    });
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
    if (jdata.length < 10)
    {
        $("select#cptIcdProcedureSelect").attr('size', jdata.length);
    }
    else
    {
        $("select#cptIcdProcedureSelect").attr('size', '10');
    };
    var options = '';
    for (var i = 0; i < jdata.length; i++)
    {
        options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
    };
    $("select#cptIcdProcedureSelect").html(options);
};

#1


29  

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>

#2


21  

You can use this keyword to access custom data, passed to $.ajax() function:

您可以使用此关键字来访问自定义数据,传递给$.ajax()函数:

    $.ajax({
        // ... // --> put ajax configuration parameters here
        yourCustomData: {param1: 'any value', time: '1h24'},  // put your custom key/value pair here
        success: successHandler
    });

    function successHandler(data, textStatus, jqXHR) {
        alert(this.yourCustomData.param1);  // shows "any value"
        console.log(this.yourCustomData.time);
    }

#3


2  

In the first code block, you're never using the str parameter. Did you mean to say the following?

在第一个代码块中,您永远不会使用str参数。你的意思是说下面的话吗?

testFunc = function(str, callback) {
    $.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: str,
        success: callback
    });
}

#4


2  

this is how I do it

我就是这么做的。

function run_ajax(obj) {
    $.ajax({
        type:"POST",
        url: prefix,
        data: obj.pdata,
        dataType: 'json',
        error: function(data) {
            //do error stuff
        },
        success: function(data) {

            if(obj.func){
                obj.func(data); 
            }

        }
    });
}

alert_func(data){
    //do what you want with data
}

var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);

#5


1  

I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)

我相信您的问题是您正在传递testFunct一个字符串,而不是一个函数对象,(这可能吗?)

#6


1  

Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:

虽然我不是百分之百确定你想要什么(也许我的大脑今天很迟钝),这里有一个类似于你所描述的用法的例子:

function GetProcedureById(procedureId)
{
    var includeMaster = true;
    pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: pString,
        datatype: "json",
        dataFilter: function(data)
        {
            var msg;
            if (typeof (JSON) !== 'undefined' &&
                    typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');
            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
        success: function(msg)
        {
            LoadProcedure(msg);
        },
        failure: function(msg)
        {
            // $("#sometextplace").text("Procedure did not load");
        }
    });
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
    if (jdata.length < 10)
    {
        $("select#cptIcdProcedureSelect").attr('size', jdata.length);
    }
    else
    {
        $("select#cptIcdProcedureSelect").attr('size', '10');
    };
    var options = '';
    for (var i = 0; i < jdata.length; i++)
    {
        options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
    };
    $("select#cptIcdProcedureSelect").html(options);
};