jquery nearest('form')不序列化

时间:2012-12-06 14:10:53

标签: jquery html ajax forms closest

我将它用作评论表格。页面上有很多这样的类,所以我必须选择最接近的形式,但它不起作用。

$(document).ready(function() {
$(".comment_but").on('click',function(){
    var location2 = $(this).closest('div');
    var datastring = $(this).closest('form').serialize();
        $.ajax({
        type: "POST",
        url: "comment_save.php",
        data:  datastring,
        cache   : false,
        success: function(html){
$('.comment_show',location2).html(html);}});});});

我的HTML

<div class="comment_show"></div>
<tr>
        <form onSubmit="return false;" name="comment_form" id="comment_form" style=" display:inline; ">
            <td align="right"><textarea name="comment_box" cols="70" rows="2"></textarea></td>
                        <td>
            <input name="post_id" type="hidden" value="<? echo($data['post_id']); ?>" />
            <input name="Send" class="comment_but" value="Comment!" type="submit" /></td>
        </form>
</tr>

1 个答案:

答案 0 :(得分:1)

将代码放在onsubmit

$(document).ready(function() {
  $("#comment_form").on("submit",function(){
    var datastring=$(this).serialize();
    $.ajax({
      type: "POST",
      url: "comment_save.php",
      data:  datastring,
      cache   : false,
      success: function(html){
        $('.comment_show',location2).html(html);
      }
    });
    return false; // mandatory
  });
});