var UsersMenu = function(){
this.returnUsers = [];
this.retrieve = function(posts){
var temp = [];
$.post("router.php", { "action": "getUsersMenu", "posts" : posts},
function(data)
{
if(data.response){
for(var i=0; i<data.returnUsers.length; i++){
temp.push(data.returnUsers[i]);
}
this.returnUsers = temp; // i know what 'this' is incorrect
}
}, "json");
alert(this.returnUsers);
}
}
2个问题:
1. 如何从 jq 对象 (returnUsers) 访问父“this”?
2. 为什么在 jq post 调用后发出警报,然后在 jq post 发出警报?
最佳答案
1 How to access to parent 'this' from jq object (returnUsers) ?
您可以在闭包中捕获它:
var UsersMenu = function() {
this.returnUsers = [];
var self = this;
this.retrieve = function(posts) {
var temp = [];
$.post("router.php", { "action": "getUsersMenu", "posts" : posts },
function(data) {
if(data.response) {
for(var i = 0; i < data.returnUsers.length; i++) {
temp.push(data.returnUsers[i]);
}
self.returnUsers = temp;
}
}, "json");
}
};
2 Why alert after jq post is calling before some alert in jq post ?
因为 AJAX 是异步的。发送 AJAX 请求的 $.post
方法会立即返回,但成功回调处理程序会在收到服务器响应后执行。所以你不应该把警报放在这个成功处理程序之外。如果您想使用 AJAX 调用的结果,这应该只发生在结果可用时的回调中。
关于javascript - 物中物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9157917/