Php getJSON与codeigniter不能正常工作

Php getJSON与codeigniter不能正常工作,php,ajax,json,codeigniter,Php,Ajax,Json,Codeigniter,我正在尝试使用codeigniter将AJAX调用方法实现到我的网站中,这就是为什么我想使用AJAX以便从数据库中获得实时更新的原因 单击按钮可以工作并显示所有JSON数据,但问题是当我尝试显示一个特定数组时,它无法识别它,它似乎在遍历每个字符 还有一件事是,当调用警报时,我可以看到html和head标记,我希望能够打印特定的数组,例如数组id“ 我做了一些事情来尝试解决它 我已经通知了数据类型,发现它是一个字符串 我已经设法让ajax在常规PHP中工作,而不是在codeigniter中工作,

我正在尝试使用codeigniter将AJAX调用方法实现到我的网站中,这就是为什么我想使用AJAX以便从数据库中获得实时更新的原因

单击按钮可以工作并显示所有JSON数据,但问题是当我尝试显示一个特定数组时,它无法识别它,它似乎在遍历每个字符

还有一件事是,当调用警报时,我可以看到html和head标记,我希望能够打印特定的数组,例如数组id“

我做了一些事情来尝试解决它

  • 我已经通知了数据类型,发现它是一个字符串

  • 我已经设法让ajax在常规PHP中工作,而不是在codeigniter中工作,所以他们的数据库没有问题

  • 我还尝试使用jQuery.parseJSON,因此我可以强制它为json,但是脚本没有运行

  • 我使用了JSONlint,它显然是一个有效的JSON

任何帮助都将不胜感激

康索尔洛格

<html>
    <head>

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAXpGbk1wkkaPiv_qkBevxAP9s4kk0oiiU&sensor=false"></script>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

[
[
    {
        "id": "1",
        "postcode": "NW6",
        "imgurl": "hello.jpeg",
        "from_user": "henny",
        "created_at": "2013-03-18 23:03:00"
    },
    {
        "id": "2",
        "postcode": "NW2",
        "imgurl": "test.jpeg",
        "from_user": "belly",
        "created_at": "2013-03-15 23:03:00"
    }
]
]
看法


您需要从控制器函数发回正确的响应头(application/json)

尝试将控制器更改为以下内容:

public function insertJSON()
{
    $this->load->model("values");
    $queryresults = $this->values->getDb();

    $arrays = array($queryresults);

    $this->output->set_content_type('application/json')
                 ->set_output(json_encode($arrays));
}

console.log(data)
而不是
alert(data)
将让您更好地查看返回的内容。使用console GTRY更新代码,而不是使用更通用的
.ajax()
方法。console.log()它似乎包含其他HTML以及您编码的json响应。是这样吗?如果您正在检索json,您的唯一输出应该是json,而不是与任何其他内容混合。是的,就是这样,它显示其他HTML,我不确定如何仅获取json我认为我做得对
<script type='text/javascript' language='javascript'>

  $('#getdata').click(function (data) {

      $.ajax({

          url: '<?php echo base_url().'index.php/welcome/insertJSON';?>',
          type: 'POST',
          cache: 'false',
          datatype: 'json'

      }).done(function (data) {

         alert(data);

      });

  });

</script>
[
[
    {
        "id": "1",
        "postcode": "NW6",
        "imgurl": "hello.jpeg",
        "from_user": "henny",
        "created_at": "2013-03-18 23:03:00"
    },
    {
        "id": "2",
        "postcode": "NW2",
        "imgurl": "test.jpeg",
        "from_user": "belly",
        "created_at": "2013-03-15 23:03:00"
    }
]
]
public function insertJSON()
{
    $this->load->model("values");
    $queryresults = $this->values->getDb();

    $arrays = array($queryresults);

    $this->output->set_content_type('application/json')
                 ->set_output(json_encode($arrays));
}