【问题标题】:getJSON not working correctly with codeignitergetJSON 无法与 codeigniter 一起正常工作
【发布时间】:2013-03-07 12:26:40
【问题描述】:

我正在尝试使用 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"
    }
]
]

控制器

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

    $arrays = array($queryresults);

    echo json_encode($arrays);  
}

查看

<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>

json_encode

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

【问题讨论】:

  • console.log(data) 而不是 alert(data) 会让您更好地了解返回的内容。
  • 使用控制台日志更新了代码
  • 尝试使用.getJSON() 而不是更通用的.ajax() 方法。
  • console.log() 中似乎包含其他 HTML,以及您编码的 json 响应。是这样吗?如果您正在检索 json,则您的唯一输出应该是 json,而不是与其他任何内容混合。
  • 是的,它显示其他 HTML,我不确定如何只抓取 JSON,我认为我做对了

标签: php ajax json codeigniter


【解决方案1】:

您需要从控制器函数发回正确的响应标头(应用程序/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));
}

【讨论】:

    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2020-08-19
    • 2013-02-06
    • 2019-02-02
    • 2021-10-15
    相关资源
    最近更新 更多