2011-08-19 80 views
2

我正在使用Codeigniter實現Backbone.js,並且很難在Ajax調用時從Codeigniter接收到適當的響應。我正在做一個#Create,它導致#save,然後#set,在那裏,它打破了,並找不到我返回數據的格式的ID。Backbone.js的正確服務器響應

出於測試目的,我回聲-ING

'[{"id":"100"}]' 

馬上回browswer,它仍然無法找到它。

任何人都知道Backbone/Codeigniter(或類似的)RESTful實現示例?

回答

9

您需要返回200個響應代碼,否則它將無法通過良好的響應。

我建幾個應用程序與骨幹/ CI組合,這是如果你使用菲爾鱘魚的REST implementation for CodeIgniter

比你控制器位於URL example.com/api/user和目錄應用程序/控制器/ 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); 
    } 

} 

它會幫助你返回正確的響應。提示:無論你返回到客戶端將被設置爲模型屬性。例如。創建用戶時,如果你只返回:

'[{"id":"100"}]' 

模型將被分配ID 100.但是,如果你返回:

'[{"id":"100", "date_created":"20-aug-2011", "created_by": "Admin", "random": "lfsdlkfskl"}]' 

這一切的鍵值對將被設置爲用戶模型(我說這只是爲清楚起見,因爲它讓我感到困惑的開始)

重要提示:這是CI 2.0+如果您使用1.7.x REST實現是一點點不同,人們關注的目錄結構

+0

謝謝!!! ...這是我一直在尋找的東西!你有一個網站,或者你有類似的教程嗎? –

+0

嗯,我有點懶惰,對我來說也是這樣(羞恥)。但你總是可以在堆棧溢出問題上發佈問題:)你也可以標記答案是正確的;) –

+0

@Ivan ...是的。我忘了標記。經過多次試驗後我發現了它! –