如何从jquery ajax里面调用parent方法成功

时间:2012-11-21 13:08:13

标签: javascript jquery ajax

  

可能重复:
  jquery reference this from parent

这是我在这里的第一篇文章。 问题 - 如何从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');
            }
        })
    }
}

2 个答案:

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

} }