質問

I used a closure to set this to _this inside the ajax success but now I have of course lost "response". Anybody know a way to retrieve the response data in this instance?

var form = {       
    name: 'great form',    
    load:function() {
        $.ajax({
        url: "get/data",
        type: "POST",
        success: function(_this){
                console.log(_this.name);     // outputs : "great form"
                console.log(response.data);  // response is undefined
        }(this)
    });
};
役に立ちましたか?

解決

You don't want to change the argument to your success handler. That first argument to the success handler is your ajax response data so you need to treat it as such.

To get access to the this pointer in your success handler, there are several methods. The one I think is the most elegant is that jQuery allows you to pass in the context that you want this to be set to in your success callback as one of the arguments to the $.ajax() function as shown here:

var form = {       
    name: 'great form',    
    load:function() {
        $.ajax({
        context: this,      // sets 'this' pointer for success callback
        url: "get/data",
        type: "POST",
        success: function(response){
                console.log(this.name);      // outputs : "great form"
                console.log(response.data);  // ajax response data
        });
    });
};

他のヒント

You don't want _this as an argument on the success function (and the way you were doing it was calling the function immediately, not waiting for jQuery to call it on success), you create it as a variable alongside the ajax call:

var form = {       
    name: 'great form',    
    load:function() {
        var _this = this; // <=== Here
        $.ajax({
        url: "get/data",
        type: "POST",
        success: function(response){
                console.log(_this.name);     // outputs : "great form"
                console.log(response.data);  // response is undefined
        }
    });
};

Of course, with that code, you could just use form.name, since it's a one-off object.

More:

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top