【发布时间】:2021-09-09 21:46:27
【问题描述】:
我有下表:z_table
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
name varchar(128) NO NULL
我的模特:
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Z_model extends CI_Model
{
protected $table = 'z_table';
public function __construct()
{
parent::__construct();
}
public function get_data($q)
{
$query = $this->connect->query($q);
$data = array();
if ($query->num_rows > 0) {
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
echo $data;
} else {
return false;
}
}
}
我的控制器:
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Z extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['z'] = $this->db->get('z_table')->result_array();
$this->load->view('z/index', $data);
} //index
public function fetch()
{
$q = "SELECT * FROM z_table ORDER BY id DESC";
$this->load->model('z_model');
$data = $this->z_model->get_data($q);
return JSON_encode($data);
} //fetch
}
我的 Ajax:
function ajaxRequest(params) {
var action = "view";
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>z/fetch",
dataType: 'json',
data: {
action: action
},
success: function(items) {
console.log(items);
params.success({
rows: items,
records: JSON.parse(items)
}, null);
},
error: function(er) {
console.log("error", er);
}
})
}
}
我想查询 z_table 并将其存储为 JSON,然后将其显示在视图中。 我认为我的 ajax 有问题,我不知道它是什么以及如何修复它。
浏览器控制台显示:
jquery.min.js:2 POST http://localhost/proj/z/fetch 500 (Internal Server Error)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
ajaxRequest @ zakat:528
calculateObjectValue @ bootstrap-table.min.js:10
value @ bootstrap-table.min.js:10
value @ bootstrap-table.min.js:10
value @ bootstrap-table-print.min.js:10
(anonymous) @ bootstrap-table.min.js:10
each @ jquery.min.js:2
each @ jquery.min.js:2
i.default.fn.bootstrapTable @ bootstrap-table.min.js:10
(anonymous) @ bootstrap-table.min.js:10
e @ jquery.min.js:2
t @ jquery.min.js:2
setTimeout (async)
(anonymous) @ jquery.min.js:2
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
fire @ jquery.min.js:2
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
ready @ jquery.min.js:2
B @ jquery.min.js:2
请指教。
【问题讨论】:
-
通过添加
error_reporting(E_ALL); ini_set('display_errors', '1');来打开 PHP 脚本中的错误以识别问题。同样在您的模型中,而不是打印数组,您应该将其返回为return $data; -
我更改了模型:class Z_model extends CI_Model { protected $table = 'z_table';公共函数 __construct() { parent::__construct(); } 公共函数 get_data($q) { $query = $this->connect->query($q); $数据 = 数组(); if ($query->num_rows > 0) { while ($row = $query->fetch_assoc()) { $data[] = $row; } 返回$数据; } 否则 { 返回假; } } } 同样的错误。我不知道如何添加php错误行_/_
-
我的 Ajax 似乎永远不会成功:function(items)
-
` url: "z/fetch"` 检查 URL 格式是否正确。您必须逐步调试并确定问题。 console.log URL 并在浏览器中点击以查看它是否会转到控制器的
fetch函数。
标签: javascript php jquery mysql json