首先,确保你正确命名你的表单输入,这将让您的生活更轻松
如果你不希望支持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