JQuery $(this) not accessible after ajax POST?

岁酱吖の 提交于 2019-12-08 01:42: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



来源:https://stackoverflow.com/questions/11027276/jquery-this-not-accessible-after-ajax-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!