我对 Ajax 和 PHP 非常陌生。我使用下面的代码通过 Ajax 提交 HTML 表单,但图像文件未通过。我尝试在代码中添加 contentType 仍然没有成功。请帮助我可以使用相同的代码(经过调整)来提交图像文件和文本输入吗?
这是代码:
$(document).ready(function() {
$("#submit_form").submit(function() {
$.ajax({
type: "POST",
url: 'inc/submit_form.php',
data:$("#submit_form").serialize(),
success: function (data) {
// Inserting html into the result div on success
$('#form-result').html(data);
},
error: function(jqXHR, text, error){
// Displaying if there are any errors
$('#form-result').html(error);
}
});
return false;
});
});
最佳答案
这只是脚本的 AJAX 部分,但这是我过去使用过的。我对每一行都进行了注释以进行解释:
<script type="text/javascript">
var files = $('#TARGET_TO_FILES_INPUT').prop('files');
var data = new FormData();
$.each(files, function(key,val){
data.append(key,val);
});
$.ajax({
type:"POST",// post method
url:UPLOAD_FILE,// path to file upload
data:data,// image and any other form data
cache:false,// stop any caching of browser
dataType:'json',// return json when complete
processData:false,// stop preprocessing of data by jquery (ie querystring)
contentType:false,// must be set to false; turns off default "application/x-www-form-urlencoded; charset=UTF-8"
success:function(o){
// successful upload stuff goes here
},
xhr:function(){
var xhr = $.ajaxSettings.xhr() ;
xhr.upload.onprogress = function(evt){
//progress bar stuff goes here
}
xhr.upload.onload = function(){
//just before upload stuff goes here
}
return xhr ;
}
});
</script>
关于javascript - 在 PHP 中使用 Ajax 提交图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31491484/