免责声明:我要问的是this的特定用法,而不是this的一般用法。所以,请没有谷歌/复制/粘贴速度的答案(:

我有下面的javascript / jquery代码:

var req = {};

function getData()
{
    var fromPage = 0;
    var toPage = 1;

    req = $.ajax({
                    url: "/_vti_bin/lists.asmx",
                    type: "POST",
                    dataType: "xml",
                    data: xmlData,
                    complete: onSuccess,
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("error: " + xhr.statusText);
                        alert(thrownError);
                    },
                    contentType: "text/xml; charset=\"utf-8\""
                });

     req.fromPage = fromPage;
     req.toPage = toPage;
}

function onSuccess(resp) {
    alert(this.fromPage);
}


我发现代码在两个地方都使用fromPage令人感到困惑(对不起,我的代码不是)。

this是引用getData内部声明的var还是req对象的一部分?或者也许是其他完全...

任何帮助表示赞赏。

最佳答案

根据jQuery.ajax文档:


  所有回调中的this引用是上下文选项中传递给设置中$ .ajax的对象;如果未指定context,则这是对Ajax设置本身的引用。


换句话说,由于未设置context选项,因此this将是作为参数传递给{...}的选项对象$.ajax

您发布的代码似乎是错误的:它从错误的对象读取fromPage。如果在options对象上设置fromPage,它将起作用:

req = $.ajax({
    //other options here...
    fromPage: fromPage
});

10-05 21:05
查看更多