【问题标题】:JSON response is empty in chrome console CodeIgniterchrome 控制台 CodeIgniter 中的 JSON 响应为空
【发布时间】:2016-11-27 10:23:19
【问题描述】:

我在访问 json 响应时遇到了奇怪的问题。

当我访问网址时:http://testproject/api/index.php/admin_customers/

JSON 响应:

[{"name":'abc'}, {"name":'def'}, "name":'xyz'}]

但是当我尝试使用 jqgrid 从 ajax 执行相同操作时,我没有收到任何数据。

我的控制器代码:

class Api extends CI_Controller {
  public function admin_customers(){
    $query = "select * from customer";
    $rows = $this->db->query($query);
    $array_rows = $rows->result();
    $json_data = json_encode($array_rows);
    header('Content-Type: application/json');
    echo $json_data;
  }
}

即使尝试过也没有运气:

return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output($json_data);

在控制台中输出响应:

我的 jQgrid JavaScript 代码是:

   $("#data-grid").jqGrid({
        url:'http://localhost/testproject/index.php/api/admin_customers/',
        mtype: "GET",
        datatype: "json",
        colModel: [
            { label: 'Name', name: 'name', key: true, width: 75, editable: true}
        ],
        editurl:'http://localhost/testproject/api/admin_customers_edit/',
        viewrecords: true,
        height: 250,
        rowNum: 20,
        pager: "#jqGridPager"
    });

我做错了什么?

无论是jQgrid,它都不会在chrome控制台中响应本身显示。

【问题讨论】:

  • 那么js代码在哪里?
  • 带有 JavaScript 代码的文件是否来自同源?我的意思是:您可以将 URL 'http://localhost/testproject/index.php/api/admin_customers/' 替换为 'testproject/index.php/api/admin_customers/' 之类的东西吗?可能是您遇到了same origin 问题。
  • 是的,它来自同一个域。我也将所有项目文件夹复制到另一个文件夹,并尝试使用localhost/testproject-api/api/admin_customers 进行休息呼叫,我正在使用localhost/testproject,但仍然看到相同的问题。是因为本地主机吗?如何处理这种情况。所有文件都应该从同一个域本身提供,因为我们目前没有其他选择

标签: php json codeigniter rest jqgrid


【解决方案1】:

@Oleg 很正常,这是跨源脚本错误。所以我终于设法通过发送额外的标头内容来允许跨源脚本,如下所示:

   public function admin_customers(){
        $query = "select * from customer";
        $rows = $this->db->query($query);
        $data = $rows->result();
        header('Content-type: application/json');
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET");
        header("Access-Control-Allow-Methods: GET, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
        echo json_encode($data, JSON_NUMERIC_CHECK);
    }

这终于解决了我的问题:)

但这是安全问题。如果我没记错的话,我们也必须在这里授权令牌。

【讨论】:

    猜你喜欢
    • 2014-05-09
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 2018-11-10
    相关资源
    最近更新 更多