Yayquery podcast mentions the$.AJAX context option.我如何在成功召唤中使用这一选择?我现在正在做的是通过输入参数返回成功的呼叫,所以我可以在成功/错误之后动画所称的ID。如果我使用了上下文选项,那么我就不必把参数退回例行程序。
In this example,I pass stateid back to the success field so that the State i s removed from the Dom once it's been deleted from the database:
$('td.delete').click(function() {
var confirm = window.confirm('Are you sure?');
if (confirm) {
var StateID = $(this).parents('tr').attr('id');
$.ajax({
url: 'Remote/State.cfc',
data: {
method: 'Delete',
'StateID': StateID
},
success: function(result) {
if (result.MSG == '') {
$('#' + result.STATEID).remove();
} else {
$('#msg').text(result.MSG).addClass('err');;
};
}
});
}
});
context所做的就是在回调中设置this的值。
因此,如果您在一个事件处理程序中,并且希望回调中的this是接收事件的元素,那么您应该这样做:
context:this,
success:function() {
//"this" is whatever the value was where this ajax call was made
}
如果你想要它是其他类型的,只要设置它,this就会引用它:
context:{some:'value'},
success:function() {
//"this" the object you passed
alert( this.some ); //"value"
}
在添加到问题中的代码中,您可以使用StateID,但实际上不需要这样做,因为您已经可以访问该变量。
var StateID = $(this).parents('tr').attr('id');
$.ajax({
url: 'Remote/State.cfc'
,data: {
method:'Delete'
,'StateID':StateID
}
,context: StateID
,success: function(result){
alert(this); // the value of StateID
alert(StateID); // same as above
if (result.MSG == '') {
$('#' + result.STATEID).remove();
} else {
$('#msg').text(result.MSG).addClass('err');;
};
}
});
哦,好吧。谢谢!我仍然在计算我想的变量范围。
@不客气。是的,这可能很棘手。可能context:最常见的用法是第一个解决方案,您希望在回调中保留与外部相同的this值。
@用户113716所以我可以选择在Ajax调用中加入这两个选项中的一个:context:{parent_group:parent_group, container: container}context:this,然后我执行console.log(this.parent_group),难道这两个都不工作吗?现在只有第一个在工作。
以防有人像我一样遇到这个问题。如果将arrow函数(() => {}分配给success选项,context将无法工作(没有错误)。您需要使用function关键字。
如果您设置了上下文选项,那么成功的this将是您设置为context的值的任何值。因此,如果传递一个包含输入参数名称和值的对象文本作为上下文,那么成功的话,可以使用this.param1获取第一个输入参数的值。
有关更多信息,请参见.ajax()文档。