php+html5使用FormData對(duì)象提交表單及上傳圖片的方法
本文實(shí)例講述了php+html5使用FormData對(duì)象提交表單及上傳圖片的方法。分享給大家供大家參考。具體分析如下:
FormData 對(duì)象,可以把form中所有表單元素的name與value組成一個(gè)queryString,提交到后臺(tái)。在使用Ajax提交時(shí),使用FormData對(duì)象可以減少拼接queryString的工作量。
使用FormData對(duì)象
1.創(chuàng)建一個(gè)FormData空對(duì)象,然后使用append方法添加key/value
formdata.append('name','fdipzone');
formdata.append('gender','male');
2.取得form對(duì)象,作為參數(shù)傳入到FormData對(duì)象
<input type="text" name="name" value="fdipzone">
<input type="text" name="gender" value="male">
</form>
var formdata = new FormData(form);
使用FormData提交表單及上傳文件:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title> FormData Demo </title>
<script src="/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'] + '" width="100">';
$('#result').html(result);
}else{
alert('提交失敗');
}
});
return false;
}
-->
</script>
</head>
<body>
<form name="form1" id="form1">
<p>name:<input type="text" name="name" ></p>
<p>gender:<input type="radio" name="gender" value="1">male <input type="radio" name="gender" value="2">female</p>
<p>photo:<input type="file" name="photo" id="photo"></p>
<p><input type="button" name="b1" value="submit" onclick="fsubmit()"></p>
</form>
<div id="result"></div>
</body>
</html>
server.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);
?>
運(yùn)行效果如下圖所示:
希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。
相關(guān)文章
php array_slice函數(shù)的使用以及參數(shù)詳解
array array_slice ( array array, int offset [, int length]),根據(jù) offset 和 length 參數(shù)所指定的 array 數(shù)組中的一段序列。offset 表示開始位置,length表示這段序列的長(zhǎng)度.2008-08-08PHP 函數(shù)學(xué)習(xí)簡(jiǎn)單小結(jié)
下面是一些php下經(jīng)常用的函數(shù),都是些必須要知道的函數(shù),只有知道有個(gè)函數(shù)與功能,才可能組裝成完整的功能強(qiáng)大的系統(tǒng)。2010-07-07Discuz5.5.0代碼高亮顯示+運(yùn)行代碼框合成插件 下載
Discuz5.5.0代碼高亮顯示+運(yùn)行代碼框合成插件 下載...2007-07-07PHP函數(shù)utf8轉(zhuǎn)gb2312編碼
PHP函數(shù)utf8轉(zhuǎn)gb2312編碼...2006-12-12PHP識(shí)別二維碼的方法(php-zbarcode安裝與使用)
這篇文章主要介紹了PHP識(shí)別二維碼的方法,通過(guò)安裝ImageMagick和php-zbarcode擴(kuò)展實(shí)現(xiàn)針對(duì)二維碼的識(shí)別功能,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-07-07