javascript对象方法无法分配ajax调用响应
我定义了以下对象:javascript对象方法无法分配ajax调用响应,javascript,ajax,object,Javascript,Ajax,Object,我定义了以下对象: var WealthyLaughingDuckControl = { initialised: false, users: [], fetchData: function() { $.ajax({ type: "GET", dataType: "json", url: "../php/client/json.php", data: {
var WealthyLaughingDuckControl = {
initialised: false,
users: [],
fetchData: function() {
$.ajax({
type: "GET",
dataType: "json",
url: "../php/client/json.php",
data: {
type: "users"
}
}).done(function(response) {
this.initialised = true;
this.users = response;
});
},
init: function() {
if (!this.initialised) {
this.fetchData();
}
},
getData: function() {
return this.users;
}
};
我正在浏览器javascript控制台中调试此对象。执行WealthLaughingDuckControl.init()前后对象的状态相同。
:
但是,我确信ajax响应工作正常,因为当我执行以下操作时:
$.ajax({
type: "GET",
dataType: "json",
url: "../php/client/json.php",
data: {
type: "users"
}
}).done(function(response) {
alert(response);
});
浏览器用
[Object Object]
提醒我。因此,我希望对象将initialized=true
和users
设置为对象响应值。上面的代码有什么错误?您需要在对对象的ajax调用中设置上下文参数,以便在ajax回调中使用它
$.ajax({
type: "GET",
dataType: "json",
context: this,
url: "../php/client/json.php",
data: {
type: "users"
}
}).done(function(response) {
this.initialised = true;
this.users = response;
});
上下文类型:PlainObject
此对象将成为所有Ajax相关回调的上下文。默认情况下,上下文是一个>对象,表示调用中使用的ajax设置($.ajaxSettings与传递给$.ajax的设置>合并)。例如,将DOM元素指定为上下文将使>的上下文成为请求的完整回调,如下所示:
什么是
response
应该返回JSON?@icanc抱歉,我不理解你的问题。
$.ajax({
type: "GET",
dataType: "json",
context: this,
url: "../php/client/json.php",
data: {
type: "users"
}
}).done(function(response) {
this.initialised = true;
this.users = response;
});
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});