json没有显示dataType:' json'

时间:2018-04-19 21:45:16

标签: javascript jquery json ajax codeigniter

我打算做一个ajax接听电话 我可以成功console.log结果而不将数据类型json放在ajax

{"id":"1","post_id":"748037498494861","post_title":"laptop","image1":"team217.jpg","price":"1234"}{"id":"2","post_id":"740811329642473","post_title":"remote control car","image1":"team522.jpg","price":"50"}{"id":"4","post_id":"316194613858174","post_title":"Ipad 3","image1":"team523.jpg","price":"400"}

当我没有它的console.log时,我得到了

     dataType: 'json',

但是我无法显示json数据 如果我把

      console.log

我的

    $(document).ready(function(){
var username = $("#usernameinfo").text();

$.ajax({
    type:"GET",


    url: "<?= base_url()?>"+"account/listings/more_user_ads",
    data: {"username":username,"pid":"<?=$this->input->get('pid')?>"},
    success: function(res){
      console.log(res);   

}


});

});

是空的 我不明白问题在哪里

 function more_user_ads(){
$post_id = $this->input->get('pid');

$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
if($query->num_rows()>0){
    foreach($query->result() as $row){
        if($post_id != $row->post_id){
       $result = array(
           'id'=> $row->id,
           'post_id'=> $row->post_id,
           'post_title'=> $row->post_title,
           'image1'=> $row->image1,
           'price'=> $row->price,
           'price'=> $row->price,

       );

       $res = json_encode($result);

        echo $res;

PHP

self.a

1 个答案:

答案 0 :(得分:1)

将每行添加到$ result数组,然后echo json_encode一次。

public function more_user_ads()
{
    $post_id  = $this->input->get('pid');
    $username = $this->input->get('username');
    $query    = $this->get_where_custom('username', $username);

    $result = []; //so we have something if there are no rows
    if($query->num_rows() > 0)
    {
        foreach($query->result() as $row)
        {
            if($post_id != $row->post_id)
            {
                $result[] = array(
                    'id'         => $row->id,
                    'post_id'    => $row->post_id,
                    'post_title' => $row->post_title,
                    'image1'     => $row->image1,
                    'price'      => $row->price,
                    'price'      => $row->price,
                );
            }
        }
    }
    echo json_encode($result);
}

实际上,您可以使用$query->result_array();来缩短这一点,因为您不必将对象转换为数组。

public function more_user_ads()
{
    $post_id  = $this->input->get('pid');
    $username = $this->input->get('username');
    $query    = $this->get_where_custom('username', $username);

    $result = []; //so we have something if there are no rows
    if($query->num_rows() > 0)
    {
        $rows = $query->result_array();
        foreach($rows as $row)
        {
            if($post_id != $row['post_id'])
            {
                $result[] = $row;
            }
        }
    }
    echo json_encode($result);
}