在 Ajax 提交后获取新的 Sql ID

Get a new Sql id after submition by Ajax

本文关键字:Sql ID 获取 Ajax 提交      更新时间:2023-09-26

使用 ajax 提交帖子的评论后,评论.php显示带有自己的 SQL 自动增量 ID 的新评论。

// Here $id comes from SQL after submit data
<div class="comment'.$id.'"><ul>
// new comment
</ul></div>

现在,如何在Ajax中获取这个新id完成:函数(数据)从注释中.php显示它发布.php页面到.

我尝试了这段不起作用的代码:

complete: function(data){
var ID = $(this).attr('id').replace('comment','');
$(".comment"+ID).append(data.responseText);
$(".comment"+ID).fadeIn(2000);
}

完整代码:

$(".repfrm").click(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
        $.ajax({
        type: "POST", url: "comment.php", data: "action=insert&author="+ author + "&replycom="+ replycom + "&url="+ url + "&img="+ img + "&parent_id="+ parent_id + "&tutid="+ tutid,
            complete: function(data){
error.fadeOut();
var ID = $(this).attr('id').replace('comment','');
$(".comment"+ID).append(data.responseText);
$(".comment"+ID).fadeIn(2000);                          

}); 
}
});
    }
    else //alert("Please fill all fields!");
error_message();
});

它有助于准确描述您的代码如何不起作用,但我想我找到了它:

var ID = $(this).attr('id').replace('comment','');

应该是

var ID = $(this).attr('class').replace('comment','');

我想你需要这个:

这用于获取最后一个插入 ID,最后一个插入的记录的 ID

将其发送到您的 ajax 回调中并附加为 ID。

如果您想知道如何从评论中发送,请告诉我们.php

你的属性不是id它是class所以使用这样的东西:

   var ID = $(this).attr('class').replace('comment','');
    $(".comment"+ID).append(data.responseText);
    $(".comment"+ID).fadeIn(2000);

有关示例,请参阅此内容:

<script> 

$( document ).ready(function() {
    var ID = $('div').attr('class').replace('comment','');
    alert(ID);
    });

</script>
</head>
<body>
<div class="comment1"></div>
</body>