gpt4 book ai didi

php - jQuery ajax 脚本无法与 PHP 中的 n 个表单一起使用

转载 作者:行者123 更新时间:2023-12-02 18:43:32 24 4
gpt4 key购买 nike

我的 AJAX jQuery 脚本和 n 个表单有一个小问题...更准确地说,PHP 脚本生成 N 个表单(表单包括一个文本区域和一个按钮),并且在 head 标签中我包含了 jquery脚本。问题是 jquery 仅适用于第一种形式,不适用于其他形式(第二,第三......)。我需要处理所有表单...这是代码:

<script>
$(document).ready(function() {
$("#submitForm").click(function() {
var text = $("#comment").val();
var id = $("#id").val();

$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}

});
});
});
</script>

这是 PHP 代码

for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>

<textarea id='comment'></textarea>
<input type='hidden' id='id' value='".$id."'/>
<input type='button' id='submitForm' value='Add Comment'>

</div>";
}

什么问题???

最佳答案

在 PHP 端,您应该进行与此类似的更改,以确保所有 html 元素都有唯一的 id。

for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>

<textarea id='comment".$i."'></textarea>
<input type='hidden' id='id".$i."' value='".$id."'/>
<input type='button' id='".$i."' class='submitForm' value='Add Comment'>

</div>";
}

并使用与此类似的内容更改 Javascript,以反射(reflect) php 端所做的更改

<script>
$(document).ready(function() {
$(".submitForm").click(function() {
var formNumber = $(this).attr("id"); // Get the form number that was clicked, the id attribute of the clicked button
var text = $("#comment"+formNumber).val(); // Get the comment of that particular form
var id = $("#id"+formNumber).val(); // get the id of that particula form

$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}

});
});
});
</script>

关于php - jQuery ajax 脚本无法与 PHP 中的 n 个表单一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16640286/

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