我有以下问题,我使用Codeigniter Controller生成Json输出。我的控制器是:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Json extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model ('functionsonproducts');
}
function index(){
$data ['rows'] = $this->functionsonproducts->getProducts ();
echo json_encode($data ['rows']);
}
}
我想得到以下结果
[{"id":"1","name":"Milk","description":"200gr","price":"10"},{"id":"3","name":"","description":"","price":"0"}]
但是当我用jquery调用Controller的函数时,比如
Jquery的
$.get("http://localhost/tddd27/index.php/json/index",
function(data){
console.log(data);
});
我得到一个未知的&lt; / HTML&GT;最后标记,所以如果我尝试使用jquery的json解析器,它会因为这个不需要的标记而产生错误。
控制台输出:
[{"id":"1","name":"Milk","description":"200gr","price":"10"},{"id":"3","name":"","description":"","price":"0"}]</html>
答案 0 :(得分:0)
不确定代码中的哪个标记来自哪个,但是返回一个;在json_endcode()语句之后,你将停止其他任何回声
答案 1 :(得分:0)
在控制器中:
class Json extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('functionsonproducts');
}
function index()
{
$functionsOnProducts = $this->functionsonproducts->getProducts();
echo json_encode($functionsOnProducts);
}
}
在视图:
中function getAllFunctionsOnProducts() {
$.ajax({type : "GET",
url : "http://localhost/tddd27/index.php/json/index",
data : { },
success : function(result){
var functionsOnProducts= jQuery.parseJSON(result);
console.log(funtionsOnProducts);
/* If you want to go through every product:
jQuery.each(functionsOnProducts,function(){
})
*/
}