gpt4 book ai didi

jquery - 使用 jquery ajax 检索响应,同时保留 "this"的范围

转载 作者:行者123 更新时间:2023-12-01 08:01:23 25 4
gpt4 key购买 nike

我在ajax成功中使用了一个闭包将其设置为_this,但现在我当然失去了“响应”。有人知道在这种情况下检索响应数据的方法吗?

var form = {       
name: 'great form',
load:function() {
$.ajax({
url: "get/data",
type: "POST",
success: function(_this){
console.log(_this.name); // outputs : "great form"
console.log(response.data); // response is undefined
}(this)
});
};

最佳答案

您不想更改成功处理程序的参数。成功处理程序的第一个参数是您的 ajax 响应数据,因此您需要这样对待它。

要访问成功处理程序中的 this 指针,有多种方法。我认为最优雅的是 jQuery 允许您传递您希望在成功回调中设置的 this 上下文,作为 $.ajax 的参数之一() 函数如下所示:

var form = {       
name: 'great form',
load:function() {
$.ajax({
context: this, // sets 'this' pointer for success callback
url: "get/data",
type: "POST",
success: function(response){
console.log(this.name); // outputs : "great form"
console.log(response.data); // ajax response data
});
});
};

关于jquery - 使用 jquery ajax 检索响应,同时保留 "this"的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19595598/

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