我正在尝试访问从php代码到jquery ajax的输出。但是我不知道为什么它返回给我整个页面的html,包括结果。有谁能告诉我这件事吗?在firefox控制台中,它显示页面html响应,包括php结果。但是在jquery代码中,console.log没有命中。
下面是jquery代码
function getprofile()
{
$.ajax({
url: 'Userpage/get_profile',
//data: {'title': title}, change this to send js object
type: "post",
dataType: 'json',
data: {'userid': 1},
success: function(data) {
console.log(data);
}
});
}
我的php代码
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Userpage extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("session");
$this->load->model("Userpage_model");
$this->load->view('Userpage_view');
}
public function index()
{
}
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit;
}
}
?>
请检查代码并告诉我哪里出错了
谢谢
发布于 2016-06-08 07:02:25
使用exit
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit; // use exit here
}
编辑
PHP使用一个名为header()
的特殊函数在呈现期间设置页面的属性。
发布于 2016-06-08 07:11:46
您需要从您的函数返回,使用exit很好,但这不是一个好的做法
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
return json_encode($data['comments']);
}
发布于 2016-06-08 09:33:24
您正在使用CI。在此ajax调用中:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
}
});
您期望在Userpage控制器内对get_profile操作进行ajax调用,该调用可能会返回:
{
"comments": [
{ ... },
{ ... },
{ ... },
...
]
}
它将记录在浏览器控制台中。
但是你得到了意想不到的结果,对吧?
我认为,您的ajax调用导致了错误。为了证明这一点,修改您的ajax调用:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// add this function to logs error
console.log(textStatus + ': ' + errorThrown);
}
});
现在,如果ajax调用导致错误,您可以在浏览器控制台中看到错误。我很确定你会在浏览器控制台中收到错误: Not Found。
如果您使用的是CI,则URL将类似于:
http://<something>/index.php/site/index
在此页面中,如果您使用url Userpage/get_profile进行ajax调用,则浏览器真正要做的是对以下内容进行ajax调用:
http://<something>/index.php/site/index/Userpage/get_profile
而不是你所期望的:
http://<something>/index.php/Userpage/get_profile
要解决这个问题,您必须在ajax调用中更改 URL 的值,以指向上面的正确URL。
通过使用CI,可以在site_url()函数的帮助下生成上面的absoulte:
site_url('Userpage/get_profile')
我通常将这个URL打印在HTML中的某个地方,然后在ajax调用期间从javascript中检索它。
https://stackoverflow.com/questions/37695381
复制