我编写了一个函数,我允许将回调传递给它。然后我想用ajax repsonse和另一个参数执行它。
我的问题是执行了回调,当我单步调试代码时,看起来函数是用适当的参数调用的,但是当实际进入回调函数时,第一个参数取值为我分配给第二个参数,第二个参数是undefined
。
这是我的功能:
namespace = {
fetch : function(sr, count, callback) {
srCount = count ? count : '25'
var sub;
if (sr == 'frontpage'){
sub = '';
}else{
sub = 'foo/' + sr + '/';
};
$.ajax({
url: "http://www.example.com/"+sub+ ".json?count=" + count,
dataType: "json",
success: function(msg)
{
callback.call(msg, count)
}
})
};
现在,当我这样称呼时:
mynamespace.fetch($(this).attr('href'), 25, true, another namespace.createPost);
我希望callback.call(msg, count)
能够解析为callback.call(/*the ajax response*/, 25);
但是,当我运行它时,我得到msg == 25
和count == 'undefined'
。我为什么不知所措......
答案 0 :(得分:4)
.call
使用第一个参数给出的显式上下文调用函数,因此callback.call(msg, count)
调用回调函数,并将msg
设置为上下文(回调中的this
值此调用的函数)和count
作为第一个参数。
所以你可能想要callback( msg, count )
或callback.call( namespace, msg, count );
这意味着回调中的this
会引用namespace
来进行该调用。
答案 1 :(得分:1)
$.ajax()
函数有一个上下文参数,您可以将其用于此目的。
$.ajax({
url: "http://www.example.com/"+sub+ ".json?count=" + count,
context: "hello",
dataType: "json",
success: function(msg)
{
// here 'this' will be the 'hello' you specified for context while making the call.
callback.call(msg, count)
}
})