一: 表单部分:
<form id="form1">
姓名:<input type="text" name="name" />
照片:<input type="file" name="photo" />
<input type="button" name="b1" value="submit" onclick="fsubmit()">
</form>
二: js部分(需引入jquery库)
<script type="text/javascript">
function fsubmit(){
var data = new FormData($('#form1')[0]);
$.ajax({
url: '2.php', //处理图片文件
type: 'POST',
data: data,
dataType: 'JSON',
cache: false,
processData: false,
contentType: false
}).done(function(ret){
if(ret){
alert(ret); //成功执行,可替换其他业务逻辑
}else{
alert(ret); //失败执行
}
});
return false;
}
</script>
三: 2.php文件后台处理图片
<?php
//接收其他文本数据
$name = isset($_POST['name'])? $_POST['name'] : '';
//图片名
$filename = time().substr($_FILES['photo']['name'], strrpos($_FILES['photo']['name'],'.'));
//保存路径
$path = './img/'.$filename;
if(move_uploaded_file($_FILES['photo']['tmp_name'], $path)){
$response = '成功';
}else{
$response = '失败';
}
echo json_encode($response);
结束!!!