3

I have been trying to use this inside an ajax function to refer the event target . but it seems that is not the way I think.

for example:

$('#test').live('click',function(){
     $.ajax({
         type:'post',
         url:
         data:...,
         success:function(mes){
             $(this).append('mes');
         }
     });
});

so here $(this) does not refer to the ('#test') selector. what does it refer to?? thanks for any explanation.

bingjie2680
  • 7,643
  • 8
  • 45
  • 72

4 Answers4

4

Inside the success callback this refers to a global object created by jQuery containing information about the AJAX rerquest. If you want to get the original DOM element you could capture it in a closure:

$('#test').live('click',function() {
    var $this = $(this);
    $.ajax({
        type: 'post',
        url: '/'
        data: { },
        success: function(mes) {
            $this.append('mes');
        }
    });
});

or if you don't like closures you could pass it as a key/value pair of the request:

$('#test').live('click',function() {
    $.ajax({
        type: 'post',
        url: '/'
        data: { },
        myElement: $(this),
        success: function(mes) {
            this.myElement.append('mes');
        }
    });
});

This could be useful in scenarios where the success callback is not an anonymous function.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

By default, this will be the extended settings object used in the AJAX call. From the documentation:

By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

You can use the context setting to specify the object this will refer to in callbacks:

$("#test").live("click", function() {
    $.ajax({
        type: "post",
        context: this,
        success: function(mes) {
            // Here, this will refer to #test.
            $(this).append('mes');
        }
    });
});
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
1

This is context. From JQuery site:
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
1

In that example, $(this) would represent the $.ajax() object.

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145