gpt4 book ai didi

javascript - json 不显示 dataType :'json'

转载 作者:行者123 更新时间:2023-12-03 02:02:59 25 4
gpt4 key购买 nike

我正在做一个 ajax get 调用我可以成功 console.log 结果,而无需将数据类型 json 放入 ajax

    dataType: 'json',

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

{"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"}

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

     dataType: '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);

}


});

});

php

 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;

最佳答案

将每一行添加到 $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);
}

关于javascript - json 不显示 dataType :'json',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49930696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com