0

可能重复:
jquery 从父级引用这个

这是我在此的头一篇博文。问题 - 如何从 ajax-success 调用警报?

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');
            }
        })
    }
}
4

2 回答 2

5

您应该在 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');
            }
        }); 
    }
};
于 2012-11-21T13:12:02.013 回答
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');
        }
}) 

} }
于 2012-11-21T13:13:57.820 回答