$ .ajax上下文选项

Phi*_*enn 62 coldfusion jquery

yayQuery播客的第11集提到$ .ajax上下文选项.如何在成功回调中使用此选项?我目前正在做的是将输入参数传递回成功回调,以便我可以设置成功/错误后调用的id的动画.如果我使用context选项,那么也许我不必从被调用的例程中传回参数.

在此示例中,我将STATEID传递回success字段,以便在从数据库中删除状态后从DOM中删除状态:

$('td.delete').click(function() {
  var confirm = window.confirm('Are you sure?');
  if (confirm) {
    var StateID = $(this).parents('tr').attr('id');
    $.ajax({
      url: 'Remote/State.cfc',
      data: {
        method: 'Delete',
        'StateID': StateID
      },
      success: function(result) {
        if (result.MSG == '') {
          $('#' + result.STATEID).remove();
        } else {
          $('#msg').text(result.MSG).addClass('err');;
        };
      }
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

use*_*716 120

所有context所做的就是设置的值this的回调.

因此,如果您在事件处理程序中,并且您希望this回调是接收事件的元素,那么您将执行以下操作:

context:this,
success:function() {
    // "this" is whatever the value was where this ajax call was made
}
Run Code Online (Sandbox Code Playgroud)

如果你想要它是其他类型,只需设置它,this并将参考:

context:{some:'value'},
success:function() {
    // "this" the object you passed
    alert( this.some ); // "value"
}
Run Code Online (Sandbox Code Playgroud)

在您添加到问题中的代码中,您可以使用StateID,但实际上并不需要,因为您已经可以访问该变量.

var StateID = $(this).parents('tr').attr('id');
$.ajax({
    url: 'Remote/State.cfc'
    ,data: {
        method:'Delete'
        ,'StateID':StateID
    }
    ,context: StateID
    ,success: function(result){

        alert(this);     // the value of StateID
        alert(StateID);  // same as above

        if (result.MSG == '') {
            $('#' + result.STATEID).remove();
        } else {
            $('#msg').text(result.MSG).addClass('err');;
        };
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 哦好的.谢谢!我还在考虑变量范围. (3认同)

jus*_*tkt 11

如果设置了上下文选项,那么this成功将是您设置的值context.因此,如果您传递包含输入参数名称和值的对象文字作为上下文,那么您可以使用this.param1获取第一个输入参数的值.

有关更多信息,请参阅.ajax()文档.