FormData对象是html5的一个对象,目前的一些主流的浏览器都已经兼容。
它是一个html5的javascript对象,非常的强大。
FormData可以凭空创建一个对象,然后往这个对象里面添加数据,然后直接提交,不需要写一行html代码,如下:
var form = new FormData();
form.append("username","name");
form.append("password","password");
$.ajax({
url:url,
type:"post",
data:form,
processData:false,
contentType:false,
success:function(data){
}
});
上传图片:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=640, user-scalable=no">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-title" content="">
<title>使用FormData对象AJAX提交文件</title>
<style>
body , input{ font-size:24px;}
</style>
</head>
<body>
<form id="fileform">
<input id="upfile" name="upfile" type="file" accept="image/*" />
</form>
<script src="https://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
<script>
//input上传的图片
$('#upfile').on('change',function(){
saveImg();
});
function saveImg(){
var formData = new FormData($('#fileform')[0]);
// formData.append('wxapp_id',10001);
// formData.append('token',token);
// formData.append('is_wechat',1);
formData.append('iFile', $('#upfile')[0].files[0]);
var dataJson = formData;
// console.log(dataJson);
$.ajax({
url: 'http://XXX/index.php?s=/api/upload/image&token='+ token +'&wxapp_id=' + wxapp_id + '&is_wechat=' + is_wechat,
type: 'post',
data: dataJson,
dataType: "json",
processData: false, // jQuery不要去处理发送的数据(使用FormData上传图片时报错解决方法)
contentType: false, // jQuery不要去设置Content-Type请求头(使用FormData上传图片时报错解决方法)
beforeSend: function() {},
success: function(response) {
console.log(response);
alert("图片上传成功");
// logo_image_id = response.data.file_id;
// logo_image_url = response.data.file_path;
},
error: function(error) { // 请求失败处理
//console.log(error);
alert("请求失败");
}
});
}
</script>
</body>
</html>