我定义了以下对象:
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 控制台中调试这个对象。 WealthyLaughingDuckControl.init()
执行前后对象状态相同:
Object {initialised: false, users: Array[0], fetchData: function, init: function, getData: function}
但是,我确定 ajax 响应可以正常工作,因为当我执行以下命令时:
$.ajax({
type: "GET",
dataType: "json",
url: "../php/client/json.php",
data: {
type: "users"
}
}).done(function(response) {
alert(response);
});
浏览器用 [Object object]
提醒我.所以我希望对象有 initialised=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;
});
context
Type: PlainObject
This object will be made the context of all Ajax-related callbacks. By default, the context is an >object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings >passed to $.ajax). For example, specifying a DOM element as the context will make that the context for >the complete callback of a request, like so:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
关于javascript对象方法无法分配ajax调用响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15712482/