Jquery Post Button

时间:2017-04-15 18:55:33

标签: jquery ajax

我有一个页面,其中有多个帖子来自数据库,在这些帖子上可以发表评论 当在文本区域写评论时我正在POST按钮上做一些ajax调用 目前我的主页只有5个帖子 问题是POST按钮工作正常只有第一篇文章我在解析之前和解析之后看到响应文本但是当我点击其他帖子POST按钮时我的控制台没有显示任何东西继承人我的代码

{'
$(document).ready(function()
{
//this will fire only when page is fully loaded
$('#comment-post-btn').each(function()
{
    $(this).click(function()
    {
 console.log("Button is working fine");
 comment_insert_btn_click();
  });
 });
 function comment_insert_btn_click()
 {
 var _comment=$('#comment-post-text').val();
 var _userId=$("#userId").val();
 var _userName=$("#userName").val();
 if(_comment.length > 0 && _userId!=null)
 {
 console.log(_comment + "UserId: " + _userId + "UserName: " + _userName);
 $.post("comment-insert.php" , 
    {
        task : "comment-insert",
        userId : _userId,
        comment: _comment
    },
        function(data)          
        {    
            console.log("ResponseTextBeforeParsing " + data);
            data = JSON.parse(data)
            console.log("ResponseTextAfterParsing " + data);

            comment_insert(data);
            console.log("ResponseTextAfterParsing " + data);

        }
    )
 $('.comment-insert-container').css('border' , ' 1px solid #fffff0');
 }
 else
 {
 $('.comment-insert-container').css('border' , ' 1px solid #ff0000');
 console.log("the text area was empty");
 }

$('#comment-post-text').val("");
}
'}

1 个答案:

答案 0 :(得分:0)

您无需使用.each()注册点击次数,且重复ID无效。因此,您要么设计一个系统来生成唯一ID,要么使用class属性。

$(".comment-post-btn").on("click", function(e) {
    var me = $(this);  // the instance that triggered the click

});

由于看起来您正在尝试获取表单值,请改为捕获表单提交。

$("form.my-form-class").on("submit", function(e) {
    e.preventDefault();

    var form = $(this);
    var data = form.serialize();
    var comment = form.find("textarea[name='comment']").val();

    $.ajax({
        ...
    });
});
相关问题