我有一个包含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调用上。当我发表评论时 //警报(URL);
事情停止工作,好像(isset($ _ FILES [&#39; image_url&#39;]))返回false。不确定......是什么导致了这个问题。
答案 0 :(得分:2)
serialize()不适用于多部分数据,相反,您应该使用Formdata()方法。看看这个stack question;也从$ .ajax中删除该警报;你不能这样做。