gpt4 book ai didi

php - 多个表单输入,如何提交并保存到mysql

转载 作者:行者123 更新时间:2023-11-29 14:16:29 26 4
gpt4 key购买 nike

我有一个照片上传系统,允许用户上传他们想要的任意数量的照片,然后我允许他们为每张照片添加描述,然后发布照片。我已经部分地进行了。我还使用 jQuery 提交表单。现在,我在尝试弄清楚如何做时遇到困难,即将每个表单元素发送到我的 php 文件,然后更新每张照片以包含描述。

<form class="upload-results-form" rel="<?php echo $albumID?>" action="javascript:return false;">
<textarea class="description" name="photoID1"></textarea>
<textarea class="description" name="photoID2"></textarea>
</form>

现在这就是我如何设置它的想法,除了可能有一个或 20 个文本区域。

为了尝试保存和发布这些,我使用 jQuery,如下所示:

$("body").on("submit", ".upload-results-form", function(){

$.ajax({
type: "POST",
url: "ajax/add/photos_publish.php",
cache: false,
success: function(html){


}
});



});

那么我怎样才能让我的 php 遍历每个 texarea 表单并保存该 photoID 的描述?

最佳答案

问题是 JQuery Ajax 不会自动为您构建 POST 数据。所以,你必须自己构建这个。您可以创建一个 JSON 对象并提交该对象(然后在 PHP 中使用 json_decode),也可以创建 urlencoded 表单数据并仅获取常规 _POST PHP 中的数组。

var _photoID1 = $('#my_form_id').find('input[name="photoID1"]').val();
var _photoID2 = $('#my_form_id').find('input[name="photoID2"]').val();

JSON 方法:

var data = { photoID1 : _photoID1, photoID2 : _photoID2 };

$("body").on("submit", ".upload-results-form", function(){
$.ajax({
type: "POST",
data: data,
url: "ajax/add/photos_publish.php",
cache: false,
success: function(html){ }
});
});

对于此方法,您可能需要添加 header 以将 Content-Type 设置为 application/json

表单POST方法:

var post_data = "photoID=" + encodeURIComponent(_photoID1)
+ "&photoID2=" + encodeURIComponent(_photoID2);

$("body").on("submit", ".upload-results-form", function(){
$.ajax({
type: "POST",
data: post_data,
url: "ajax/add/photos_publish.php",
cache: false,
success: function(html){ }
});
});

这两种方式都会将您的数据发送到服务器。

(上面的代码没有完全调试,但基本正确。)

关于php - 多个表单输入,如何提交并保存到mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12576036/

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