首先,確保你正確命名你的表單輸入,這將讓您的生活更輕鬆
如果你不希望支持IE8/9爲您的AJAX上傳功能,您可以使用以下:
// FormData is not supported by ie8 and 9 as far as I know
// and some others see here: http://caniuse.com/#search=FormData
// you can check for FormData support by something like this
var supportFormData = function(){
return !! window.FormData;
};
$('#form_new_product').submit(function(e) {
e.preventDefault();
var form;
// you can pass in your form element here if you have the <input> tags named correctly, like this:
form = new FormData($("#form_new_product").eq(0)) // that's the easiest way
// or you can create a FormData object and append stuff to it
form = new FormData();
// signature --> form.append(input[name], input[value])
form.append('product_name', $('#form_new_product input[name="product_name"]').val());
form.append('product_description', $('#form_new_productinput[name="product_description"]').val());
// now a file input,
form.append('product_image', $('#form_new_product input[type="file"]').eq(0).files[0], 'image.png'/*optional*/);
return $.ajax({
url: '/path/to/form/action',
type: 'POST',
data: form,
mimeType:'multipart/form-data",
contentType: false,
cache: false,
processData: false
)
.done(function(response){
// handle success
})
.fail(function(response){
// handle error
});
});
如果你想支持IE8和IE9,你可能需要做一些小調整服務器端,以及, 和你submitForm功能也不會像以前那樣簡單,我想小號使用http://malsup.com/jquery/form/ 最喜歡的一些其他答案,但作爲插件提到,here 服務器響應頭務必爲text/html
因此,IE8不會觸發文件下載的JSON響應(假設您期待JSON響應) - 基本上這個插件創建一個帶有表單的iFrame並將其提交給服務器。除text/html
之外還有其他解決方案,比如用<textarea>
包裝響應,請檢查我提到的最後一個鏈接。
所以,假設你使用這個插件,這裏是我會做的。
var isIE = function() {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
$('#form_new_product').submit(function(e) {
e.preventDefault();
var $form = $("#form_new_product");
var options = {
url: '/path/to/form/action',
type: "POST",
mimeType: "multipart/form-data"
};
// hack because IE lt 9 iFrame triggers a file download for a application/json response
// http://stackoverflow.com/questions/17701992/ie-iframe-doesnt-handle-application-json-response-properly
if (Reporting.util.isIE() <= 9) {
// maybe you have another contract with the server, like a custom query string or whatever
// but the server needs to return text/html
options.ContentType = "text/html";
}
// don't think this returns a promise, so you can use the options.success and options.error like that
options.success = function(response){
// handle success
};
options.error = function(response){
// handle error
};
// or you really want to return a promise, then you can
var deferred = new $.Deferred();
options.success(function(response){
deferred.resolve(response);
});
options.error(function(response){
deferred.reject(response);
})
// this will submit all of your inputs
form.ajaxSubmit(options);
return deferred;
});
要支持IE8和IE9嗎? – bentael