如何在$ .ajax的成功回调中传递$(this)
我已经看到访问$(this)的一些不同示例是ajax的成功回调,但是没有一个给我我想要的答案-他们都在ajax函数中访问$(this),我想传递$(this )到一个单独的功能.
I have seen a few different examples of accessing $(this) is the success callback of ajax but none give me the answer I want - they all access $(this) within the ajax function, I want to pass $(this) to a separate function.
所以如果有两个文本框需要验证
So if there are 2 textboxes that need to be validated
$("#tb1").focusout(function(){
$.ajax({
type:'POST',
url: 'validURL',
data: {various_parameters},
contentType: 'application/json; charset=utf-8',
dataType:'json',
success: function(data){
validInput(data, $(this));
},
error: error
});
}
$("#tb2").focusout(function(){
$.ajax({
type:'POST',
url: 'validURL',
data: {various_parameters},
contentType: 'application/json; charset=utf-8',
dataType:'json',
success: function(data){
validInput(data, $(this));
},
error: error
});
}
function validInput(response, obj){
console.log(response.d);
console.log(obj.val());
};
当我运行代码时,我得到了response.d的正确值,但出现了一个错误:jquery-1.11.1.min.js:4 Uncaught TypeError:无法读取obj.val()的undefined属性"toLowerCase".
When I run the code I get the correct value for response.d but an error : jquery-1.11.1.min.js:4 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined for obj.val().
我做错什么了吗?
感谢您的帮助. 请参阅:执行/运行
Thanks for any help. See:Dos/Run
$(this)
是相对于最内层函数的,在这种情况下,您需要在ajax查询之前将$(this)
分配给变量,并在成功中使用该变量.
$(this)
is relative to the inner-most function, and in this case you'll need to assign $(this)
to a variable before the ajax query, and use that variable in the success instead.
$("#tb1").focusout(function(){
var elem = $(this);
$.ajax({
type:'POST',
url: 'validURL',
data: {various_parameters},
contentType: 'application/json; charset=utf-8',
dataType:'json',
success: function(data){
validInput(data, elem);
},
error: error
});
}