【发布时间】:2016-11-11 18:40:13
【问题描述】:
我有一个包含 4 个文本字段和一个图像文件的表单。我必须通过 AJAX 调用上传它。工作 2 天后......我已经成功了......但是有一个问题
<script type="text/javascript">
$(document).ready(function(){
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
//alert(files);
}
$("#myProfileForm").submit(function(event){
event.preventDefault();
document.getElementById("messageBlock").style.display = 'none';
// Serialize the form data.
var form = $('#myProfileForm');
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
url: $(form).attr('action')+'?'+files,
data: formData
alert(url);
}).done(function(response) {
var formMessages = $('#form-messages');
if(response.error){
document.getElementById("messageBlock").style.display = 'block';
$(formMessages).html(response.message);
}else{
document.getElementById("messageBlock").style.display = 'block';
$(formMessages).html(response.message);
}
})
});
});
</script>
我的 PHP 文件代码:
if (isset($_FILES['image_url'])){
$name = $_FILES['image_url']['name'];
$image_url = $name;
$temp_name = $_FILES['image_url']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = 'uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
//echo 'File uploaded successfully';
$image_url = UPLOADED_IMG_URL.''.$location.''.$name;
}
}
} else {
$image_url = DEFAULT_IMAGE;
}
}else {
$image_url = '../../API/v1/uploads/default.PNG';
}
PHP 代码运行良好。问题在于 AJAX 调用。当我评论 //alert(url);
如果 (isset($_FILES['image_url'])) 返回 false,事情就会停止工作。不确定..是什么导致了问题。
【问题讨论】:
-
对象应由
key : value对组成。你不能只放一个alert(url)。