适用于Backbone.js的服务器响应

Wil*_*ham 2 backbone.js

我正在使用Codeigniter实现Backbone.js,并且在Ajax调用时很难从Codeigniter接收正确的响应.我正在做一个#Create,导致#save,然后是#set,就在那里,它中断了,无法找到我返回数据的格式的ID.

出于测试目的,我正在回应

    '[{"id":"100"}]'
Run Code Online (Sandbox Code Playgroud)

回到眉毛,仍然找不到它.

任何人都知道Backbone/Codeigniter(或类似的)RESTful实现示例?

Iva*_*nić 9

您需要返回200个响应代码,否则它将无法通过响应.

我使用Backbone/CI组合构建了一些应用程序,如果你使用Phil Sturgeon的REST实现CodeIgniter会容易得多

比你位于url example.com/api/user和目录应用程序/ controllers/api/user.php的控制器看起来像这样:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

include APPPATH.'core/REST_Controller.php';  // MUST HAVE THIS LINE!!!

class User extends REST_Controller {

    // update user   
    public function index_put() // prefix http verbs with index_
    {
        $this->load->model('Administration');
        if($this->Administration->update_user($this->request->body)){ // MUST USE request->body
            $this->response(NULL, 200); // this is how you return response with success code
            return;
        }
        $this->response(NULL, 400); // this is how you return response with error code
    }

    // create user
    public function index_post()
    {
        $this->load->model('Administration');
        $new_id = $this->Administration->add_user($this->request->body);
        if($new_id){
            $this->response(array('id' => $new_id), 200); // return json to client (you must set json to default response format in app/config/rest.php
            return;
        }
        $this->response(NULL, 400);
    }

    // deleting user
    public function index_delete($id)
    {
        $this->load->model('Administration');
        if($this->Administration->delete_user($id)){
            $this->response(NULL, 200);
            return;
        }
        $this->response(NULL, 400);
    }

}
Run Code Online (Sandbox Code Playgroud)

它将帮助您返回正确的答案.

提示:无论您返回客户端的任何内容都将设置为模型属性.例如,当您仅返回时创建用户:

'[{"id":"100"}]'
Run Code Online (Sandbox Code Playgroud)

model将被赋予id 100.但如果你返回:

'[{"id":"100", "date_created":"20-aug-2011", "created_by": "Admin", "random": "lfsdlkfskl"}]'
Run Code Online (Sandbox Code Playgroud)

所有这些键值对都将被设置为用户模型(为了清楚起见,我添加了这个,因为它在开始时让我很困惑)

重要提示:如果您使用的是1.7.x,那么这适用于CI 2.0+.REST实现与目录结构有点不同