Codeigniter RESTful API not returning JSON


Codeigniter RESTful API not returning JSON

我有一个应用程序,我使用Codeigniter作为后端,Backbone作为前端。现在我使用 https://github.com/philsturgeon/codeigniter-restserver 的 RESTful API。我想获取RSS提要,所以我创建了一个RSS模型.php application->models

<?php
    class Rss_model extends CI_Model
    {
        var $table_name = 'artist_news';
        var $primary_key    = 'news_id';
    function get_all_rss_feeds()
    {
        $this->db->select($this->primary_key);
        $this->db->from($this->table_name);
        return $this->db->get();
    }
   }
?>

然后在application->controllers年,我创建了创建文件rss.php的文件夹api

<?php
require(APPPATH.'libraries/REST_Controller.php');
class rss extends REST_Controller{
public function get_all_rss_feeds_get()  
{ 
    $this->load->database();
    $this->load->model('rss_model');
    $data = $this->rss_model->get_all_rss_feeds();
    if($data) {
        $this->response($data, 200); 
    } else {
        $this->response(array('error' => 'Couldn''t find any news!'), 404);
    }
 }
}
?>

到目前为止一切顺利,它返回了一个带有大量 rss 提要的文本数组,但不是JSON格式,这是我的前端需要的格式。

有谁知道这里的问题是什么?

提前感谢...

[编辑]

我的主干代码如下所示:

function (App, Backbone) {
    var Rss = App.module();
    Rss.View = Backbone.View.extend({
        template: 'rss',
        initialize: function() {
            this.listenTo(this.collection, 'all', this.render)
        },
        serialize: function() {
            return this.collection ? this.collection.toJSON() : [];
        }
    });
    Rss.RssCollection = Backbone.Collection.extend({
        url: function() {
            return '/myproject/index.php/api/rss/get_all_rss_feeds/';
        }
      });
    return Rss;
}

转到 config/rest.php 文件并找到这一行:

$config['rest_default_format'] = 'xml';

将其更改为 :

$config['rest_default_format'] = 'json';

我认为您错过了模型中返回的结果,请检查以下内容

function get_all_rss_feeds()
{
    $this->db->select($this->primary_key);
    $this->db->from($this->table_name);
    return $this->db->get()->result();
}

如果你对 Phil Sturgeon REST 库进行签名,你需要在 URL 中附加格式类型。例:

http://example.com/books.json
http://example.com/books?format=json

如果你想要另一种格式,比如XML,你只需要在URI中传递新格式,不需要改变代码中的任何内容。例:

http://example.com/books.xml
http://example.com/books?format=xml

延伸阅读:

内容类型部分 - https://github.com/philsturgeon/codeigniter-restserver