JQuery的$不是(这个)AJAX POST后访问?不是、JQuery、POST、AJAX

2023-09-10 17:54:19 作者:是药三分毒是爱三分伤

比方说,我有一大堆的共享click事件链接:

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>

和在$('。做-的东西)。单击功能我执行该更新数据库与东西jQuery的AJAX POST请求,我也得到一个成功的响应。阿贾克斯完成后,我只是想更改链接文本的价值是什么我送回来从服务器...

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);
  }
});

});

此调用就好了,我验证了result.d的确是来自服务器的文本,但文本没有改变。我认为,$(本)元素不再访问的AJAX后门柱?我能做些什么来解决这个?

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?

推荐答案

在一般当你失去上下文这样,可以省下引用的对象。像这样的:

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);
        }
    );
}