JQuery $(this) not accessible after ajax POST?

2019-05-27 08:54发布

问题:

Let's say I have a bunch of links that share a click event:

<a href="#" class="do-stuff">Click me</a>
<a href="#" class="do-stuff">Click me</a>
<a href="#" class="do-stuff">Click me</a>
<a href="#" class="do-stuff">Click me</a>

and in the $('.do-stuff').click function I execute a JQuery ajax POST request that updates the database with stuff and I get a successful response. After the ajax is completed, I simply want to change the value of the link text to be whatever I send back from the server...

$('.do-stuff').click(function () {
$.ajax({
  type: "POST",
  url: "MyWebService.asmx/DoSomething",
  data: '{CurrentLinkText: "'+ $(this).text() +'"}',
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (result) {
    $(this).text(result.d);
  },
  error: function (XMLHttpRequest, textStatus, errorThrown) {
    alert(textStatus);
  }
});

});

This invoked just fine and I verified that "result.d" is indeed the text from the server but the text is not changing. I think that the $(this) element is no longer accessible after the AJAX post? What can I do to work around this?

回答1:

In general when you lose context like that, you can save a reference to the object. Like this:

function clickHandler() {
    var that = this;
    $.ajax( { url: '#',
        success: function (result) {
            $(that).text(result.d);
        }
    );
}


回答2:

See here: $(this) inside of AJAX success not working

You can set the context option:

This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). (...)

Example:

$.ajax({
    //...
    context: this,
    success: function(json) {
        //...
    }
});

or use $.proxy:

$.ajax({
    //...
    success: $.proxy(function(json) {
         //...
    }, this)
});


回答3:

Try:

success: $.proxy(function(result) {
         //...
    }, this)


回答4:

There are lots of ways to do this, as you can see from the answers here. Personally, I prefer to construct a function bound to the current value of this:

success: (function(target) {
              return function(result) {
                   $(target).text(result.d);
              }
         })(this)

It's neat, clean, and $(this) will remain the same as it is in the outer context; i.e. it will be the element that raised the event.



回答5:

jQuery('#youridvalue').html(result.d);
jQuery('.yourclassvalue').html(result.d);

Use it