jquery 向回调函数传参数

本文介绍如何使用jQuery的.post函数结合JavaScript闭包技术,在AJAX请求中传递额外参数,并保持这些参数的作用域,以便在回调函数中使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


The solution is the binding of variables through closure.

I haven't used the .post function in jQuery, but a quick scan of the document suggests the call back should be a function pointer accepting the following:

function callBack(data, textStatus) {};

Therefore I think the solution is as follows:

var doSomething = function(extraStuff) {
    return function(data, textStatus) {
        // do something with extraStuff
    };
};

var clicked = function() {
    var extraStuff = {
        myParam1: 'foo',
        myParam2: 'bar'
    }; // an object / whatever extra params you wish to pass.

    $.post("someurl.php", someData, doSomething(extraStuff), "json");
};

What is happening?

In the last line, doSomething(extraStuff) is invoked and the result of that invocation is a function pointer.

Because extraStuff is passed as an argument to doSomething it is within scope of thedoSomething function.

When extraStuff is referenced in the returned anonymous inner function of doSomething it is bound by closure to the outer function's extraStuff argument. This is true even after doSomethinghas returned.

I haven't tested the above, but I've written very similar code in the last 24 hours and it works as I've described.

You can of course pass multiple variables instead of a single 'extraStuff' object depending on your personal preference/coding standards.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值