gpt4 book ai didi

javascript - 在ajax post请求中传递第二个参数

转载 作者:行者123 更新时间:2023-11-29 17:44:40 25 4
gpt4 key购买 nike

我在互联网上找到了一个关于如何使用 ajax 和 php 上传多个文件的解决方案。在 ajax 请求中,我正在传递带有选择要上传的文件的表单,但我需要再添加一个参数,但是当我这样做时,它不起作用。我不擅长 php,我尝试以多种方式传递第二个参数,但都没有用。我如何传递第二个参数,以便一切正常?

html:

<form method="post" enctype="multipart/form-data">
Select files to upload:
<input name="file[]" type="file" multiple>
<input type="button" onclick="upload(this)" value="Upload"/>
</form>

JavaScript:

function upload(element) {
var formData = new FormData($(element).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
success: function (callback) {
// some code
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}

PHP

<?php
$mysqli = include 'connection.php';

$total = count($_FILES['file']['name']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
for ($i = 0; $i < $total; $i++) {
$name = $_FILES['file']['name'][$i];
$size = $_FILES['file']['size'][$i];
$location = 'uploads/';
$target_file = $location . basename($name);
if (isset($name)) {
if (empty($name)) {
echo 'Please choose a file' . "\n";
} else if (file_exists($target_file)) {
echo 'File already exists.' . "\n";
} else if ($size > 1000000) {
echo 'File is too large' . "\n";
} else {
$tmp_name = $_FILES['file']['tmp_name'][$i];
$statement = $mysqli->prepare("INSERT INTO files (name, subjectId) VALUES (?, ?)");
$str = '1'; // here I would like to set variable using $_POST
$statement->bind_param('ss', $name, $str);

if (move_uploaded_file($tmp_name, $location . $name)) {
if ($statement->execute()) {
echo 'File successfully uploaded :' . $location . $name . "\n";
} else {
echo 'Error while executing sql' . "\n";
}
} else {
echo 'Error while uploading file on server' . "\n";
}
}
}
}
}

所以我想得到的是在 javascript 中添加第二个参数:

data: formData, mySecondParameter

然后在 php 中,当我为 sql 绑定(bind)参数时,我想输入我从 javascript 传递的变量:

$str = $_POST['contentOfMySecondParameter'];

最佳答案

您可以使用 FormData.append()添加更多参数。

    var formData = new FormData($(element).parents('form')[0]);
formData.append('mySecondParameter', contentOfMySecondParameter);

然后在PHP中使用$_POST['mySecondParameter']获取这个参数。

关于javascript - 在ajax post请求中传递第二个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50729819/

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