这是我在这里的第一篇文章。 问题 - 如何从ajax成功调用警报?
var page = {
alerts: function (json) {
if (json == 'us') { alert("blablabla") } else {
alert(json.login);
}
},
ajax: function (obj) {
$.ajax({
type: 'post',
url: './scripts/serv.php',
dataType: 'json',
data: { object: $.base64.encode(JSON.stringify(obj)) },
success: function (json) {
// how to call from here alerts(json)?? this.alerts(json) - doesn't
// work only page.alerts(json) but i think its wrong way.
},
error: function (json) {
alert('ajax failed');
}
})
}
}
答案 0 :(得分:4)
您应该在AJAX请求之前存储对此的引用,因为从不同的范围调用success
。
示例:
var page = {
alerts: function(json){
if (json=='us'){ alert("blablabla")} else{
alert(json.login); }
},
ajax: function(obj){
var me = this;
$.ajax({
type:'post',
url:'./scripts/serv.php',
dataType:'json',
data:{object:$.base64.encode(JSON.stringify(obj))},
success: function(json){
// how to call from here alerts(json)?? this.alerts(json) - doesn't work only page.alerts(json) but i think its wrong way.
me.alerts(json);
},
error: function(json){
alert('ajax failed');
}
});
}
};
答案 1 :(得分:1)
var page={
alerts: function(json){
if (json=='us'){ alert("blablabla")} else{
alert(json.login); }
},
ajax: function(obj){
var that = this; <!-- PARENT OBJECT REFERENCE -->
$.ajax({
type:'post',
url:'./scripts/serv.php',
dataType:'json',
data:{object:$.base64.encode(JSON.stringify(obj))},
success: function(json){
that.alerts(json) <!-- USE THAT -->
},
error: function(json){
alert('ajax failed');
}
})
} }