Ajax成功函数在codeigniter中重复加载div

时间:2016-04-07 07:52:26

标签: php ajax codeigniter

我的ajax代码就在这里,

成功功能总是显示两次。

如果我在数据库中有两条记录意味着它会两次检索这两行,三行意味着检索两次

<script type="text/javascript">
            $(document).ready(function()
            {
                $('form#form1').submit(function(e) {
                    var form = $(this);
                    var srpid = form.find('#srpid').val();
                    //$('#cmd_'+srpid).html(" ");
                    e.preventDefault();
                    $.ajax({
                        'type': "POST",
                         url: "<?php echo base_url('pages/post/comments'); ?>",
                        'data': form.serialize(), // <--- THIS IS THE CHANGE
                        //dataType: "html",
                        'success': function(data){
                            $('#cmd_'+srpid).html(data);
                        },
                        //error: function() { alert("Error posting feed."); }
                   });
                  return false;
                });     
            });
            </script>


        <div class="post-scroll" id="cmd_<?php echo $post_id; ?>">
    <?php 
    $command = $this->db->order_by('comment_date','DSC')->where('post_id',$post_id)->get('sr_post_comment')->result();
    foreach($command as $cmd){ 
                    $usercmdview = $this->db->get_where('users',array('id' => $cmd->user_id))->result();
    ?>
     <div class="post-cnt"  style="float:left;">
        <div class="post-img">
             <img src="<?php echo $usercmdview[0]->image; ?>" />
        </div>
        <div class="post-name">
            <p><?php echo $usercmdview[0]->firstname." "; ?><br /><span><?php echo  $cmd->comment_date; ?></span></p> 
        </div>
        <div class="post-cmd">
             <p class="cmdlist_<?php echo $cmd->comment_id; ?>"><?php echo $cmd->comments; ?></p>
        </div>
     </div>
 <?php } ?>
</div>  

1 个答案:

答案 0 :(得分:0)

您在&#34;提交&#34;定义了ajax请求行动,但你没有停止表格提交。这意味着当您点击&#34;提交&#34;按钮,将执行以下操作。

  1. ajax将数据提交给服务器
  2. 表单也提交,它将刷新页面。
  3. &#13;
    &#13;
    <script type="text/javascript">
        $(document).ready(function(){
            $('form#form1').submit(function(e) {
                ...
                return false;
            });     
        });
    </script>
    &#13;
    &#13;
    &#13;