我正在使用Codeigniter实现Backbone.js,并且很难在Ajax调用时从Codeigniter接收到适当的响应。我正在做一个#Create,它导致#save,然后#set,在那里,它打破了,并找不到我返回数据的格式的ID。Backbone.js的正确服务器响应
出于测试目的,我回声-ING
'[{"id":"100"}]'
马上回browswer,它仍然无法找到它。
任何人都知道Backbone/Codeigniter(或类似的)RESTful实现示例?
我正在使用Codeigniter实现Backbone.js,并且很难在Ajax调用时从Codeigniter接收到适当的响应。我正在做一个#Create,它导致#save,然后#set,在那里,它打破了,并找不到我返回数据的格式的ID。Backbone.js的正确服务器响应
出于测试目的,我回声-ING
'[{"id":"100"}]'
马上回browswer,它仍然无法找到它。
任何人都知道Backbone/Codeigniter(或类似的)RESTful实现示例?
您需要返回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实现是一点点不同,人们关注的目录结构
谢谢!!! ...这是我一直在寻找的东西!你有一个网站,或者你有类似的教程吗? –
嗯,我有点懒惰,对我来说也是这样(羞耻)。但你总是可以在堆栈溢出问题上发布问题:)你也可以标记答案是正确的;) –
@Ivan ...是的。我忘了标记。经过多次试验后我发现了它! –