如何将'this'作为上下文传递给$ .ajax调用

时间:2012-03-19 17:07:53

标签: javascript jquery jquery-plugins

我已将此示例缩减为最低限度的代码。 我专注于'this'关键字。

以下是我调用Ajax插件的方法:

settings.context = this;
myXHR = $(this).myAjax('myComponent.cfc',settings);

我想要做的是使用$(this)作为上下文,以便调用例程不必设置 settings.context = this;

这是我到目前为止所得到的,但我知道我做错了:

!function($, window, document, undefined) {
    $.fn.myAjax.myOptions = {
        type: 'POST',
        dataType: 'json'
    }
    $.fn.myAjax = function(myURL, mySettings) {
        var local = {};
        local.settings = $.extend({}, $.fn.myOptions, mySettings);
        local.settings.context = this;
        local.XHR = $.ajax(myURL,local.settings)
        return local.XHR;
    };
}(jQuery, window, document);

1 个答案:

答案 0 :(得分:0)

!function($, window, undefined) {
    var document = window.document;
    $('#msg').ajaxStart(function() {
      $(this).empty().removeClass('alert alert-info');
    });
    var Variables = {};
    Variables.settings = {
        type: 'post',
        dataType: 'json',
        async:false
    };
    $.fn.myAjax = function(myURL, mySettings) {
        var local = {};

        mySettings = $.extend({}, Variables.settings, {context:this[0]}, mySettings);
        local.$xhr = $.ajax(myURL,mySettings); // myURL += '?returnFormat=json&queryFormat=column'
        local.$xhr.done(function(result) {
            if (result.MSG) {
                $('#msg').html(result.MSG).addClass('alert alert-error');
            }
        });
        local.$xhr.fail(function(jqXHR, textStatus, errorThrown) {
            $('#msg').html(textStatus + ': ' + errorThrown).addClass('alert alert-error');
        });
        return local.$xhr; // return this.each()
    };
}(jQuery, window);