【问题标题】:Passing this object to xhr function jquery将此对象传递给 xhr 函数 jquery
【发布时间】:2015-09-01 05:30:10
【问题描述】:

我正在尝试将 this 对象作为参数从 ajax xhr 传递给外部函数,但它似乎不起作用。下面是我的代码。

  $(document).on("click", "#imgform_submit", function (e) {
    e.preventDefault();

    var thiss = $(this);          //  $(this)  object
    var href = window.location.href;
    var form_id = href.substr(href.lastIndexOf('/') + 1);
    var formData = new FormData($("form#imgform")[0]);
    $.ajax({
        url: base_url + "index.php/init/add_img/" + form_id,
        type: 'POST',
        data: formData,
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        xhr: function () {  // custom xhr
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) { // Check if upload property exists
                myXhr.upload.addEventListener('progress', progressHandler(thiss), false);// For handling the progress of the upload
            }
            return myXhr;
        },
        success: function (data) {
            if(data == "true"){
                 $("#file_upload_container").html("<div class='msg'>File Successfully Uploaded</div>");
             }

        },
        complete: function () { //     
        }

    });

});

progressHandler

 function progressHandler(e, thiss) {
    $(thiss).hide();     //this line is not working.
    var progress = document.getElementById('progress');
    //  var status = document.getElementById('status');
    var percent = (e.loaded / e.total) * 100;
    percent = Math.round(percent);
    progress.style.width = Math.round(percent) + '%';
    //  status.innerHTML = percent + '% completed.';
}

上面我将this 作为参数传递给函数progressHandler 并尝试访问它。我没有工作。帮帮我。

已编辑

我忘了提一件事。 #imgform_submit 按钮由 jquery 代码触发为:

$(document).on("click", ".uploadimg", function (e) {
    e.preventDefault();

    var filebrowser = $(this).prev().prev(".uploadContainer").children("#file_browser");
    var inputfile = filebrowser.children('.upload');
    if (inputfile.val() == '') {
        alert("Please select file before uploading.");
    } else {
        $("#imgform").prepend(filebrowser);
        $("#imgform_submit").trigger("click");
    }
});

现在我想将.uploadimg 按钮的this 对象传递给#imgform_submit 函数,类似于progressHanlder 函数。最后,progressHanlder 应该可以使用.uploadimgthis 对象。我试过。

 $(document).on("click", ".uploadimg", function (e) {
   //some code
 $("#imgform_submit").trigger("click", $(this));

还有

 $(document).on("click", "#imgform_submit", function (e, thiss) {
     $(thiss).hide();   // .uploadimg button is hidden here. works well.
     myXhr.upload.addEventListener('progress', progressHandler(thiss), false);  //passing thiss object of .uploadimg to progressHandler 
 });

 function progressHandler(e, thiss) {
    $(thiss).hide();    //it didnot worked here.
 })

上面我写的是快捷方式。 .uploadimg this 对象现在不能在 progressHandler 函数中工作。如何克服这种情况。

【问题讨论】:

  • 你可以使用 JSON.stringify($(form_data).serialize())

标签: javascript jquery ajax object this


【解决方案1】:

似乎正在调用progressHandler函数

myXhr.upload.addEventListener('progress', progressHandler(thiss), false)

?

尝试使用.bind()

myXhr.upload.addEventListener('progress', progressHandler.bind(e.target), false)

progressHandler 删除thiss 作为参数,使用$(this) 作为选择器

function progressHandler(e) {
    $(this).hide();     //this line is not working.
    var progress = document.getElementById('progress');
    //  var status = document.getElementById('status');
    var percent = (e.loaded / e.total) * 100;
    percent = Math.round(percent);
    progress.style.width = Math.round(percent) + '%';
    //  status.innerHTML = percent + '% completed.';
}

【讨论】:

  • 我正在尝试将单击的按钮#imgform_submit 对象绑定到progressHandler 函数。但是您的代码似乎绑定了另一个 this 对象。
  • @user254153 在click 事件e.target 应该是#imgform_submit : this ;试试$(document).on("click", "#imgform_submit", function (e) {console.log(e.target)})progressHandlerfunction progressHandler(e) {console.log(this)};见developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 我试过了,但没用。 $(this).hide() 应该在 progressHandler 函数中隐藏单击的按钮。但是点击的按钮没有隐藏。
  • @user254153 可以创建jsfiddlejsfiddle.net来演示吗? console.log(this)progressHandler 内返回什么?
  • 返回被点击的按钮元素。我认为你的代码是正确的。我误解了。实际上,当单击其他按钮时,我正在从 jquery 代码中触发 #imgform_submit 按钮。现在,我如何将this 对象传递给触发函数。我将编辑我的问题。感谢您的帮助。
【解决方案2】:

您的问题是,您没有将方法 progressHandler 传递给事件侦听器。你正在做的是以你的this对象作为第一个参数执行方法,并使用执行的返回值(即undefined)作为事件监听器的回调。

你可以用一个匿名函数来解决这个问题,它会像你需要的那样执行你需要的函数:

myXhr.upload.addEventListener('progress', function (e) {
    progressHandler.call(thiss, e);
}, false);

因此,您要做的是将一个函数传递给执行您的progressHandler 的侦听器,同时将thiss 作为this 对象和e 作为第一个参数传递。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/call

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2011-12-07
    • 2016-03-30
    相关资源
    最近更新 更多