gpt4 book ai didi

jquery - $.ajax 上下文选项

转载 作者:IT王子 更新时间:2023-10-29 03:26:44 25 4
gpt4 key购买 nike

yayQuery 的第 11 集播客提到 $.ajax context option .我将如何在成功回调中使用此选项?我目前正在做的是将我的输入参数传递回成功回调,以便我可以为成功/错误后调用的 id 设置动画。如果我使用上下文选项,那么也许我不必从被调用例程传回参数。

在这个例子中,我将 STATEID 传回成功字段,以便状态从数据库中删除后从 DOM 中删除:

$('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');;
};
}
});

关于jquery - $.ajax 上下文选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5097191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com