Codeigniter PHP JSON发送HTML响应

Codeigniter PHP JSON发送HTML响应,php,json,codeigniter,Php,Json,Codeigniter,我对Codeigniter和JSON有问题。这是我的代码: $.post("Admin/Admin/addschool", {test: 'test'}, function(data){ if (data.status == 'ok') alert(data); else alert(data); }, "json"); 。。。在我的控制器中: public function addschool() { $data = array("st

我对Codeigniter和JSON有问题。这是我的代码:

$.post("Admin/Admin/addschool", {test: 'test'}, function(data){             
  if (data.status == 'ok')
    alert(data);
  else 
    alert(data);
}, "json");
。。。在我的控制器中:

public function addschool() {
  $data = array("status" => "ok", "message"=> "something ");  
  echo json_encode($data);  
  exit(); 
}
但是每次我的json回复时,我都会使用整个视图的HTML,例如我的响应

<!doctype html>

<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://localhost:10090/css/layout.css" />
<title>Administration</title>
<meta name="description" content="">
<meta name="author" content="">
</head>

管理

首先,最好不要使用“echo”,而是使用“return”。尝试将控制器直接放在url上,看看返回的json是否使用绝对url

$.post("/Admin/Admin/addschool", {test: 'test'}, function(data){             
  if (data.status == 'ok')
    alert(data);
  else 
    alert(data);
}, "json");
最好是返回然后退出内部代码点火器功能

public function addschool() {
  $data = array("status" => "ok", "message"=> "something ");  
  echo json_encode($data);  
  return; 
}

可能是url有问题。让我举一个url路由问题的例子

比如说,admin controller index函数加载admin主页,因此在load方法中,在url部分,如果您只写“addschool”,ajax调用将转到addschool函数

链接是自动完成的,admin/addschool

例如,函数admin/load\u view 加载你的查看页面,现在如果你在url中键入addschool,链接将发生,url将变为

管理员/加载视图/添加学校


因此,您必须检查加载视图页面的codeigniter函数,然后使用适当的链接

尝试在浏览器url栏中运行此函数。检查返回的内容。还可以尝试使用函数(数据、状态、xhr)$这->输出->设置输出(json编码($data));退出()在控制器的构造函数中有一些视图吗?包含ajax调用的文件,它的路径是什么?您可能需要
/Admin/Admin/addschool
来代替。他没有返回任何内容,而是
将它回显到浏览器中。codeigniter会自动为每个请求发送html(布局)。他想让那东西失效,而不是你的答案。