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>