【发布时间】: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 应该可以使用.uploadimg 的this 对象。我试过。
$(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