我在访问 json 响应时遇到奇怪的问题。
当我访问网址时:http://testproject/api/index.php/admin_customers/
JSON 响应:
[{"name":'abc'}, {"name":'def'}, "name":'xyz'}]
但是当我尝试使用 jqgrid 从 ajax 执行相同操作时,我没有收到任何数据。
我的 Controller 代码:
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控制台中显示响应本身。
最佳答案
@Oleg 是仪式,这是跨源脚本错误。所以我最终设法通过发送额外的 header 内容来允许跨源脚本来做到这一点,如下所示:
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);
}
这终于解决了我的问题:)
但这是安全问题。如果我没记错的话,我们也必须在这里授权 token 。
关于php - Chrome 控制台 CodeIgniter 中的 JSON 响应为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38544665/