我花了一段时间研究,但无法弄清楚这一点。
对于网站上的评论部分,我有一个表单可以输入您的评论+评级,添加一些照片,我希望使用AJAX和jQuery通过PHP脚本处理。使用常规POST没有Ajax工作,所以我确定HTML很好,我的Javascript关闭。当我尝试使用以下代码发送图像时,它不会接收图像或列表只有1个图像和一个损坏的文件路径。
HTML代码
<form action='javascript:void(0)' enctype='multipart/form-data' id='author-review-form'>
<input type='text' class='form-control' id='authorRating' name='authorRating' placeholder='4.6'>
<textarea class='form-control' id='authorReview' name='authorReview' rows='4'></textarea>
<input type='file' id='authorImg' name='authorImg' style='display:none;' multiple>
<button class='btn btn-primary' type='submit'><i class='fa fa-comment-o'></i> Post comment</button>
</form>
的Javascript
$('#author-review-form').submit(function(e) {
e.preventDefault();
var form = new FormData($('#author-review-form')[0]);
$.ajax({
url: "scripts/add-comment.php",
method: "POST",
data: form,
processData: false,
contentType: false,
success: function(result){
console.log("Response:\n"+result);
},
error: function(er){
console.log("Error\n"+er);
}
});
});
然后我的PHP处理
<?php
session_start();
include 'functions.php';
extract($_POST);
$user = $_SESSION['username'];
$productID = $_SESSION['product-view'];
//Check receiving data
echo "Rating $authorRating\n";
echo "Review $authorReview\n";
if(count($_FILES['authorImg']['name'])>0) echo "Files received\n";
else echo "No files received\n";
echo "Files received ".count($_FILES['authorImg']['name'])."\n";
for($i=0;$i<count($_FILES['authorImg']['name']);$i++) {
$tmpFile = $_FILES['authorImg']['tmp_name'][$i];
echo "File $i at $tmpFile\n";
}
?>
非常感谢任何使用AJAX向PHP发布多个图像的帮助。
答案 0 :(得分:3)
Html代码
<form action='javascript:void(0)' enctype='multipart/form-data' id='author-review-form'>
<input type='text' class='form-control' id='authorRating' name='authorRating' placeholder='4.6'>
<textarea class='form-control' id='authorReview' name='authorReview' rows='4'></textarea>
<input type='file' id='authorImg' name='authorImg[]' style='display:none;' multiple><!-- we are sending multiple files hence this should be an array like this-->
<button class='btn btn-primary' type='submit'><i class='fa fa-comment-o'></i> Post comment</button>
</form>
相同的PHP代码
<?php
session_start();
include 'functions.php';
extract($_POST);
$user = $_SESSION['username'];
$productID = $_SESSION['product-view'];
//Check receiving data
echo "Rating $authorRating\n";
echo "Review $authorReview\n";
//the files send from the fontend is as an array so we should use a for loop
//you can print the $_FILES and see the indexes and give the loop accordingly
for($i=0;$i<count($_FILES['authorImg']);$i++){
$tmpFile = $_FILES['authorImg'][$i]['tmp_name'][$i];
echo "File $i at $tmpFile\n";
}
?>