Php 使用AJAX生成和提交多个表单
我正在建立一个论坛网站,但我很难弄清楚为什么我的AJAX代码不能正常工作。问题是: 我正在通过while循环为用户发表的每一篇文章生成多个表单(评论部分),我编写了以下AJAX脚本:Php 使用AJAX生成和提交多个表单,php,ajax,Php,Ajax,我正在建立一个论坛网站,但我很难弄清楚为什么我的AJAX代码不能正常工作。问题是: 我正在通过while循环为用户发表的每一篇文章生成多个表单(评论部分),我编写了以下AJAX脚本: <script type="text/javascript"> $(document).ready(function() { $(".comment_submit2").click(function(){ var topic_id = <?php echo $_GET['
<script type="text/javascript">
$(document).ready(function()
{
$(".comment_submit2").click(function(){
var topic_id = <?php echo $_GET['id']; ?>;
var post_id = // receiving the id from the form
$.ajax({
type: "POST",
url: "comment_on_post.php",
data: {topic_id: topic_id,post_id : post_id,comment : $('textarea#commenting2').val() }, //success on the first post only
//data: $(this).serialize(), not working at all..
cache: false,
success: function(data){
alert(data);
location.replace("topic2.php?id=<?php echo $_GET['id']; ?>");
}
});
return false;
});
});
</script>
<?php
include 'dbh.php';
//some other stuff...
$result_posts = $conn -> prepare("SELECT * FROM posts WHERE post_topic=:post_topic ORDER BY DATE(post_date) ASC");
$result_posts -> bindParam(':post_topic',$topic_id);
$result_posts -> execute();
while ($row2 = $result_posts ->fetch(PDO::FETCH_ASSOC))
{
?>
//some other stuff...
<form name="form2" id=" <?php echo $row2['post_id']; ?> ">
<textarea id="commenting2" placeholder="Leave a comment" cols="30"rows="5"></textarea>
<br>
<input type="submit" class="comment_submit2" value="Comment">
</form>
//I need to pass the value id of form to ajax
//some other stuff...
<?php } ?>
$(文档).ready(函数()
{
$(“.comment_submit2”)。单击(函数(){
var topic_id=;
var post_id=//从表单接收id
$.ajax({
类型:“POST”,
url:“comment_on_post.php”,
数据:{topic_id:topic_id,post_id:post_id,comment:$('textarea#commenting2').val(),//仅第一篇文章成功
//数据:$(此).serialize(),完全不工作。。
cache:false,
成功:功能(数据){
警报(数据);
location.replace(“topic2.php?id=”);
}
});
返回false;
});
});
//其他一些东西。。。
此代码仅适用于第一篇文章。我试图
序列化()
,但我认为我做错了什么。有人有办法解决这个问题吗?ID必须是唯一的,$('textarea#commenting2')
将获取具有该ID的第一个文本区域的内容,而不是当前形式的内容。您应该使用class=“commenting2”
而不是ID,然后使用DOM遍历来查找当前表单中的textarea
data: {topic_id: topic_id, post_id: this.form.id ,comment : $(this).siblings('textarea.commenting2').val() },
它正在工作(没有post\u id),但是如何将post\u id传递到ajax?
这个.form.id
将返回表单的id。
data: {topic_id: topic_id, post_id: this.form.id ,comment : $(this).siblings('textarea.commenting2').val() },