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

被折叠的 条评论
为什么被折叠?



