0

以下 Ajax 工作

function Retrieve(el) {
    var table = this;
    this.el = el;
    this.fetchInfo = function () {
        $.ajax('data.html', {
            context: table,
            <!-- QUESTION HERE -->
            data: {
                location: table.data('location')
            },
            success: function (response) {
                this.el.find('.info').html(response).fadeIn();
            },
        }
        }

但我想知道为什么我不能在表示的线上table.data替换为。this.data由于我将上下文设置为table变量,this现在应该设置table为所指的内容吗?这适用于 Ajax 对象的其他成员(包括success)的上下文,但不适用于data. 为什么会这样?

data('name')从具有属性的标签中提取值data-name

4

2 回答 2

1

context您提供的变量仅适用于success回调中,并且不会更改任何其他传递给$.ajax.

因此,答案取决于您实际调用 fetchInfo. 变量将data:在任何上下文中解析fetchInfo。鉴于您遇到问题,这表明您没有Retrieve以对象作为其上下文来调用该函数。

编辑这一行是你的问题:

this.el.on('click', 'button', this.fetchInfo);

仅仅因为您提到了this.fetchInfo, 并不会this在随后调用它时创建上下文。试试这个:

this.el.on('click', 'button', $.proxy(this.fetchInfo, this));
于 2013-07-31T07:52:27.903 回答
0

查看 的文档$.ajax()我发现context设置为callbackContext变量。这与 use success, error, beforeSend,一起使用complete,但与dataoption 无关。

AJAX 选项被分配给一个名为的变量s

s = jQuery.ajaxSetup({}, options),

data 选项被转换为字符串,但callBackContext未被使用。

// Convert data if not already a string
if (s.data && s.processData && typeof s.data !== "string") {
    s.data = jQuery.param(s.data, s.traditional);
}

因此有必要设置指定元素以data使用除 之外的变量this

于 2013-08-29T08:23:47.507 回答