0

我有以下问题,我使用 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 调用控制器的函数时,比如

jQuery

  $.get("http://localhost/tddd27/index.php/json/index",
    function(data){
     console.log(data);
    });

最后我得到一个未知的 </html> 标签,所以如果我尝试使用 jquery 的 json 解析器,它会因为这个不需要的标签而产生错误。

控制台输出:

[{"id":"1","name":"Milk","description":"200gr","price":"10"},{"id":"3","name":"","description":"","price":"0"}]</html>
4

2 回答 2

0

not sure where in your code that tag is coming from, but put a return; after the json_endcode() statement and you'll stop anything else from being echo'd

于 2013-04-13T09:38:37.353 回答
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(){
            })
            */
}
于 2013-04-14T14:09:23.167 回答