gpt4 book ai didi

javascript - AJAX上传文件和文本不起作用

转载 作者:行者123 更新时间:2023-12-01 05:43:13 24 4
gpt4 key购买 nike

我使用这个ajax代码来提交表单并上传多个输入文件。我想通过ajax发送所有表单数据。通过ajax发送文本输入成功,但文件输入未成功!如何更改此代码?

$("#add_order").click(function () {

//*****get data input
var formData = new FormData();
formData.append( 'action', 'add_order');
formData.append( 'customer_name', $('input[name=customer_name]').val());
formData.append( 'date', $('input[name=date]').val());
formData.append( 'order_status', $('input:radio[name=order_stautus]').val());
formData.append( 'total_price', $('input[name=totalprice]').val());
formData.append( 'quits', $('input[name=quits]').val());
formData.append( 'debt', $('input[name=debt]').val());
formData.append( 'desc', $('#desc').val());
formData.append( 'desc2', $('#desc2').val());

$.each($("input[type=file]"), function(i, obj) {
$.each(obj.files,function(j,file){
formData.append('photo['+i+']', file);
});
});
$.ajax({
url: "includes/ajax/ajax.php",
data: formData,
processData: false,
contentType: 'multipart/form-data',
type: 'POST',
dataType:'json',
success: function(response){
//load json data from server and output message
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="alert alert-danger">'+response.text+'</div>';
}else{
output = '<div class="alert alert-danger">'+response.text+'</div>';
}
$("#results").append(output).slideDown();
}
});
});

获取表单数据的PHP代码:

if($_POST['action']=='add_order'){

$customer_id = 1;
$date = $_POST['date'];
$status = $_POST['order_status'];
$total_price = $_POST['total_price'];
$quits = $_POST['quits'];
$debt = $_POST['debt'];
$desc = $_POST['desc'];
$desc2 = $_POST['desc2'];

for($i=0; $i<count($_FILES['photo']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['photo']['tmp_name'][$i];

//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "../../uploads/orders/" . $_FILES['photo']['name'][$i];

//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {

//Handle other code here

}
}
}

formData控制台.log: enter image description here

最佳答案

根据this , contentType 必须设置为 false 才能上传 ajax 文件。

也许可以尝试将所有文​​件命名为 photo[] 而不是 photo[n],以便让您的 PHP 服务器处理数组转换。请参阅http://php.net/manual/en/features.file-upload.multiple.php .

关于javascript - AJAX上传文件和文本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29550575/

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