gpt4 book ai didi

javascript - jQuery POST 数据使用 FormData 和 PHP

转载 作者:行者123 更新时间:2023-12-01 05:11:36 25 4
gpt4 key购买 nike

我正在尝试使用 ajax、jquery、formdata 发布数据,然后使用 php 处理它,我无法看到在我的 PHP 文件中处理它的错误在哪里。最终结果是一个空数组。

HTML 代码

<form action="ajax.php?action=upload" method="POST" name="submit_upload_album" id="submit_upload_album" enctype="multipart/form-data">
<input type="hidden" id="input1" name="input1" value="input1">
<input type="hidden" id="input2" name="input2" value="input2">
<input type="hidden" id="input3" name="input3" value="input3">
<input type="hidden" id="input4" name="input4" value="false">
<input type="hidden" id="input5" name="input5">
<input type="hidden" id="input6" name="input6" value="auto">
<input id="title" name="title" class="form-control" type="text" maxlength="70" required/>
<textarea id="description" class="form-control" name="description" rows="4" style="resize: vertical;"></textarea>
<input id="file1" type="file" name="fileupload[]" accept="video/*" required/>
<input id="file2" type="file" name="fileupload[]" accept="audio/*" required/>
<input id="file3" type="file" name="fileupload[]" accept="video/*" required/>
</form>

JS代码

<script type="text/javascript">
$(document).ready(function(e){
// Submit form data via Ajax
$("#submit_upload_album").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: "ajax.php?action=upload",
data: new FormData(this),
async: true,
beforeSend: function(){
/*$('input[type=submit]').attr("disabled","disabled");*/
},
success: function(response){
$('#answer').html(response);
},
contentType: false,
cache: false,
processData:false
});
});
});
</script>

PHP 代码

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
echo '<pre>';
var_dump($_FILES);
echo '<br>';
var_dump($_POST);
echo '</pre>';
?>

结果

array(0) {}

array(0) {}

最佳答案

$(this) 在 ajax 请求中无法访问,您应该按如下方式修改代码:

$("#submit_upload_album").on('submit', function(e){
e.preventDefault();
let formData = $(this).serialize();
$.ajax({
type: 'POST',
url: "ajax.php?action=upload",
data: new FormData(formData),
async: true,
beforeSend: function(){
/*$('input[type=submit]').attr("disabled","disabled");*/
},
success: function(response){
$('#answer').html(response);
},
contentType: false,
cache: false,
processData:false
});
});

希望这对您有帮助

关于javascript - jQuery POST 数据使用 FormData 和 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61727527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com