gpt4 book ai didi

javascript - 如何在提交表单时包含 id?

转载 作者:行者123 更新时间:2023-11-28 15:19:58 24 4
gpt4 key购买 nike



目标:
1. 提交上传表单时包含id(本例中id=1),以便可以在submit.php中访问

2.根据id将文件名插入sql数据库。

形式:

<form action="#" enctype="multipart/form-data" method="post">
<input type="hidden" name="name" id="1">
<input type="file" name="upload" id="upload" >
<input class="button" type="submit" name="submit" value="Submit Content">
</form>

脚本:

$('input[type=file]').on('change', prepareUpload);
$('form').on('submit', uploadFiles);

function prepareUpload(event)
{
files = event.target.files;
}

function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();

var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});

$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
console.log('Successfully uploaded the file');
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('Failed to upload the file');
}
});
}


submit.php

<?php 
$data = array();

if(isset($_GET['files']))
{
$error = false;
$files = array();

$uploaddir = 'uploads/';

foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);
?>


非常感谢!

最佳答案

您可以将隐藏字段用作

<input type="hidden" name="my_id" id="my_id" value="1">

现在在你的 jquery 中只需使用

var my_id = $('#my_id').val();

并用数据传递它

关于javascript - 如何在提交表单时包含 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31933776/

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