我有以下代码在javascript中创建一个类....现在我只传递'网站'的ID,然后通过ajax调用我将从数据库中获取其余的信息(JSON ENCODED )。
现在我唯一的问题是,当我看到最后一个对象中的什么时,它只显示了id。
ajax调用工作正常,因为如果我在成功后警告this.address(ajax)它会显示结果。
我认为我不能用ajax请求设置属性......你能帮忙吗?
function website(id) {
this.id = id; //id
$.ajax({ //website_information
type: "GET",
url: '/proc.php?proc=website_name&id=' + this.id + '',
success: function(data){
var tmp = $.parseJSON(data);
this.address = tmp.website_address;
this.name = tmp.website_name;
}
});
}
var obj = new website('20');
obj.alertwebsite();
console.log(obj);
答案 0 :(得分:5)
这里有两个问题。首先是$.ajax
是异步的。这意味着它在请求完成之前返回。 success
函数在请求完成时运行,但obj.alertwebsite()
将在之前运行。
第二个问题是AJAX回调中this
的值。在回调中,this
设置为包含AJAX调用的所有设置的对象。这意味着您要在此对象上设置address
和name
属性。有两种方法可以解决这个问题。第一个是that = this
和其他答案一样。更好的方法是在AJAX调用中使用context
设置:
function website(id) {
this.id = id; //id
$.ajax({ //website_information
type: "GET",
url: '/proc.php?proc=website_name&id=' + this.id + '',
context: this,
success: function (data) {
var tmp = $.parseJSON(data);
this.address = tmp.website_address;
this.name = tmp.website_name;
}
});
}
这允许您自定义this
在回调中的含义。这在the jQuery AJAX documentation中有记录。
答案 1 :(得分:2)
AJAX回调中的this
可能并不是指构造函数正在构建的“对象”。相反,我们通过将this
放在另一个变量中来保留that
,例如that
。然后我们使用function website(id) {
var that = this; //preserve "this"
this.id = id;
$.ajax({
type: "GET",
url: '/proc.php?proc=website_name&id=' + this.id + '',
success: function(data){
var tmp = $.parseJSON(data);
that.address = tmp.website_address; //using "that"
that.name = tmp.website_name; //using "that"
}
});
}
来引用我们在AJAX回调中的对象。
obj.alertwebsite()
另外,您在that.address
盲目致电,因为您不知道您的网站信息(that.name
和{{1}})是否已加载。
答案 2 :(得分:1)
function website(id) {
// you need to save "this"
var self = this;
this.id = id; //id
$.ajax({ //website_information
type: "GET",
url: '/proc.php?proc=website_name&id=' + this.id + '',
//async: false, // optionally, if you want to get it back syncronously, so the console.log after the function call will already have the data
success: function(data){
var tmp = $.parseJSON(data);
// you need to use the saved "this"
self.address = tmp.website_address;
self.name = tmp.website_name;
}
});
}