FormData 对象,可以把form中所有表单元素的name与value组成一个queryString,提交到后台。在使用Ajax提交时,使用FormData对象可以减少拼接queryString的工作量。
使用FormData对象
1.创建一个FormData空对象,然后使用append方法添加key/value
复制代码 代码如下:
var formdata = new FormData();
formdata.append('name','fdipzone');
formdata.append('gender','male');
2.取得form对象,作为参数传入到FormData对象
复制代码 代码如下:
<form>
<input type="text" value="fdipzone">
<input type="text" value="male">
</form>
复制代码 代码如下:
var form = document.getElementById('form1');
var formdata = new FormData(form);
使用FormData提交表单及上传文件:
复制代码 代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title> FormData Demo </title>
<script src="https://www.jb51.net/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
<!--
function fsubmit(){
var data = new FormData($('#form1')[0]);
$.ajax({
url: 'server.php',
type: 'POST',
data: data,
dataType: 'JSON',
cache: false,
processData: false,
contentType: false
}).done(function(ret){
if(ret['isSuccess']){
var result = '';
result += 'name=' + ret['name'] + '<br>';
result += 'gender=' + ret['gender'] + '<br>';
result += '<img src="' + ret['photo'] + '">';
$('#result').html(result);
}else{
alert('提交失敗');
}
});
return false;
}
-->
</script>
</head>
<body>
<form>
<p>name:<input type="text" ></p>
<p>gender:<input type="radio" value="1">male <input type="radio" value="2">female</p>
<p>photo:<input type="file"></p>
<p><input type="button" value="submit"></p>
</form>
<div></div>
</body>
</html>
server.php如下:
复制代码 代码如下:
<?php
$name = isset($_POST['name'])? $_POST['name'] : '';
$gender = isset($_POST['gender'])? $_POST['gender'] : '';
$filename = time().substr($_FILES['photo']['name'], strrpos($_FILES['photo']['name'],'.'));
$response = array();
if(move_uploaded_file($_FILES['photo']['tmp_name'], $filename)){
$response['isSuccess'] = true;
$response['name'] = $name;
$response['gender'] = $gender;
$response['photo'] = $filename;
}else{
$response['isSuccess'] = false;
}
echo json_encode($response);
?>
运行效果如下图所示: