<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
window.console && console.log(file_data);
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'test9.php', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
if(response)
window.parent.document.getElementById('img').src=response;
//$('#msg').html(response); // display success response from the server
console.log(response);
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
}
);
</script>
<?php
if(!empty($_FILES['file']['name'])){
//判断是否有文件
$fileinfo = $_FILES['file']; //将文件信息赋给变量$fileinfo
if($fileinfo['size']<1000000 && $fileinfo['size']>0){ //判断文件大小
if(move_uploaded_file($_FILES["file"]['tmp_name'],"image/".$fileinfo['name']))
{
$filepath="image/".$fileinfo['name'];
echo $filepath;
}
}
}
php echo是向浏览器输出值,return是函数返回
1.ajax请求从服务器端读取返回值,而且这些返回值必须为一些可读的数据类型, 例如json或html。为了打印这些返回值 需要echo,但是return则不会打印出来数据 它只是简单的在服务器上传递数据。
2.Ajax获取返回值是使用HTTP请求。 return不会产生输出(只在server端进行),而echo可以(从server -> brower,http协议)。Ajax请求的url其实就是一个页面,它可以在浏览器显示,而 php中以return返回数据只是在服务器端去返回这些数据。
综上所述,如果ajax 地址是一个PHP return,将不会获取到正确数据。