【问题标题】:Couldn't get records from database and load in view through ajax无法从数据库中获取记录并通过 ajax 加载到视图中
【发布时间】:2016-11-16 02:42:27
【问题描述】:

这里我想获取记录并希望使用 ajax 显示在视图中。在这里我无法获取 json 数据。如果我得到了,传递给视图的正确方法是什么。 通过这个,我想从表中获取用户名和 cmets,并希望使用 ajax 在点击事件中显示。 我想像 Facebook 一样,当用户 cmet 时,评论显示没有页面加载。

控制器:

public function get_comments()
{

            $query=$this->db->query("SELECT user_name,comments FROM user_comments join user_reg where user_reg.user_id=user_comments.user_id");
            $temp = $query->result();
            foreach($temp as $row)
            {
                header('Content-Type: application/json');
                echo json_encode($row); 

            }
            exit();

}

查看:

<form action="" method="post" name="usercomments" id="usercomments"> 
            <div>
                <textarea name="comment" form="usrform" placeholder="Enter comment here..." id="ucom"></textarea>
                </br>

                <div class="tab-group">
                <input type="submit" class="button button-block tab" id="submitbutton" value="Comment"/>
                </div>
            </div>

        </form> 

    $(document).ready(function()
    {

        $("#submitbutton").click(function(event)
        {
            //alert('hiii');
            event.preventDefault();

            jQuery.ajax({
                type:"POST",
                url:"<?php echo base_url();?>index.php/welcome/get_comments",
                dataType:"json",
                data:"",
                success:function(data)
                {
                    console.log(data);
                    alert(data);
                } 


            });



        });

    });

【问题讨论】:

  • 提交表单时会发生什么?您在控制台中收到任何错误吗?您是否收到任何服务器端错误作为响应?这里没有足够的信息。
  • 当我提交表单时,记录被插入,但我无法获取它们。没有任何错误,我也无法在控制台中获取信息。

标签: jquery mysql ajax codeigniter


【解决方案1】:

您应该尝试将“echo json_encode”放在循环之外。

使用一个数组来存储你的行并json_encode这个数组。

【讨论】:

【解决方案2】:

尝试这些方法。我们正在将行重建为更易于阅读的客户端对象,并在循环之外对其进行编码。你也不需要像那样设置标题。

$query=$this->db->query("SELECT user_name,comments FROM user_comments join user_reg where user_reg.user_id=user_comments.user_id");
$temp = $query->result();
$response = array();
foreach($temp as $row){
   $user = $row['user_name'];
   $response[$user][] = $row['user_comments'];
}
echo json_encode($response); 

【讨论】:

    猜你喜欢
    • 2014-09-09
    • 2013-07-20
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多