0

Я только начал использовать библиотеку отдыха, написанную Phil Sturgeon. Я начал использовать его, написав несколько простых примеров. Мне не хватает работы «post» и «get», но не для put и delete. У меня есть некоторые вопросы, основанные на приведенном ниже коде.Проблема с остатком Codeigniter с позвоночником

// a simple backbone model 
var User = Backbone.Model.extend({ 
    urlRoot: '/user', 
    defaults:{ 
     'name':'John', 
     'age': 17 
    } 
}); 

var user1 = new User(); 
//user1.save(); // request method will be post unless the id attr is specified(put) 
//user1.fetch(); // request method will be get unless the id attr is specified 
//user1.destroy(); // request method will be Delete with id attr specified 

В моем CI REST контроллер

class User extends REST_Controller 
{ 
    public function index_get() 
    { 
     echo $this->get(null); //I can see the response data 
    } 

    public function index_post() 
    { 
     echo $this->post(null); //I can see the response data 
    } 

    public function index_put() 
    { 

    } 

    public function index_delete() 
    { 

    } 
} 

В принципе, и опубликовать в контроллере будет вызываться при сохранении модели или принести модель. С идентификатором, указанным в модели, я могу сделать запрос put или delete серверу с помощью model.save() и model.destroy(). однако, я получил ошибку сервера. похоже, что index_put или index_delete не могут быть вызваны. Кто-нибудь знает Как я могу обращаться:

  1. запрос положить в контроллер
  2. удаления запроса в контроллере
  3. получить одну запись с идентификатором указанного

С мерзавцем, я только видел его перечислить index_post и index_put. нет демо-версии index_put и index_delete. должен ли кто-нибудь помочь мне? спасибо

+0

Кто-нибудь может мне помочь? – eded

ответ

2

Я столкнулся с такой же точной проблемой, похоже, что методы DELETE, PUT, PATCH еще не поддерживаются браузерами/html/сервером. Вы можете посмотреть на этом переполнение стека вопрос: Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

простое решение было бы изменить methodMap магистральной линии 1191 к следующему:

// Map from CRUD to HTTP for our default `Backbone.sync` implementation. 
var methodMap = { 
    'create': 'POST', 
    'update': 'POST',  //'PUT', 
    'patch': 'POST',  //'PATCH', 
    'delete': 'POST',  //'DELETE', 
    'read': 'GET' 
}; 

, а затем включают в себя тип действия в качестве атрибута модель

var Person = Backbone.Model.extend({ 
     defaults:{ 
     action_type : null, 
     /* 
      * rest of the attributes goes here 
      */ 
     }, 
     url : 'index.php/person' 
}); 

теперь, когда вы хотите сохранить модель, сделайте следующее

var person = new Person({ action_type: 'create' }); 
person.set(attribute , value); // do this for all attributes 
person.save(); 

в application/controllers папке вы должны иметь контроллер под названием person.php с классом по имени Person расширения REST_Controller, который имеет следующие методы:

class Person extends REST_Controller { 

    function index_get() { /* this method will be invoked by read action */ } 

    /* the reason those methods are prefixed with underscore is to make them 
    * private, not invokable by code ignitor router. Also, because delete is 
    * might be a reserved word 
    */ 

    function _create() { /* insert new record */ } 
    function _update() { /* update existing record */ } 
    function _delete() { /* delete this record */ } 
    function _patch() { /* patch this record */ } 

    function index_post() { 

     $action_type = $this->post('action_type'); 
     switch($action_type){ 

      case 'create' : $this->_create(); break; 
      case 'update' : $this->_update(); break; 
      case 'delete' : $this->_delete(); break; 
      case 'patch' : $this->_patch(); break; 
      default: 
       $this->response(array('Action '. $action_type .' not Found' , 404)); 
       break; 

     } 
    } 
} 

Сказав, что это решение является уродливым один. Если вы перечисляете в реализации магистральной, вы найдете следующий код в строке 1160:

// For older servers, emulate HTTP by mimicking the HTTP method with `_method` 
// And an `X-HTTP-Method-Override` header. 
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { 
    params.type = 'POST'; 

что означает, что вам нужно, чтобы установить параметры эмулировать системообразующие конфигурации.добавьте следующие строки в main.js

Backbone.emulateHTTP = true; 
Backbone.emulateJSON = true; 

Чтобы проверить эффект, который я создал простую модель, и вот результаты

вам нужен контроллер под названием Api в applications/controllers папке в файле с именем api.php

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

require_once APPPATH.'/libraries/REST_Controller.php'; 

class Api extends REST_Controller 
{ 

    function index_get() 
    { 
    $this->response(array("GET is invoked")); 
    } 

    function index_put() 
    { 
    $this->response(array("PUT is invoked")); 
    } 

    function index_post() 
    { 
    $this->response(array("POST is invoked")); 
    } 

    function index_patch() 
    { 
    $this->response(array("PATCH is invoked")); 
    } 

    function index_delete() 
    { 
    $this->response(array("DELETE is invoked")); 
    } 

} 

и в вашей папке js/models, создать модель под названием api_model.js

var Api = Backbone.Model.extend({ 
     defaults:{ 
      id:  null, 
      name: null 
     }, 
     url: "index.php/api/" 
}); 

var api = new Api(); 

api.fetch({ success: function(r,s) { console.log(s); } }); // GET is invoked 

api.save({},{ success: function(r,s) { console.log(s); } }); // POST is invoked 

//to make the record old (api.isNew() = false now) 
api.save({id:1},{ success: function(r,s) { console.log(s); } }); // PUT is invoked 

api.destroy({ success: function(r,s) { console.log(s); } }); //DELETE is invoked 

Я не знаю, как сделать патч, но надеюсь, что это поможет.

Редактировать

я узнал, как сделать патч, который не входит в реализации остальной код воспламенителя. В REST_Controller строке 39, вы найдете следующее,

protected $allowed_http_methods = array('get', 'delete', 'post', 'put'); 

вам нужно добавить 'patch' в конце, чтобы принять этот метод, а также, после выполнения этого добавьте этот код

/** 
* The arguments for the PATCH request method 
* 
* @var array 
*/ 
protected $_patch_args = array(); 

также, вам необходимо добавить следующий код для разбора аргументов патча:

/** 
* Parse PATCH 
*/ 
protected function _parse_patch() 
{ 
    // It might be a HTTP body 
    if ($this->request->format) 
    { 
     $this->request->body = file_get_contents('php://input'); 
    } 

    // If no file type is provided, this is probably just arguments 
    else 
    { 
     parse_str(file_get_contents('php://input'), $this->_patch_args); 
    } 
} 

Теперь, по магистральным документации, вам необходимо пройти {patch: true} послать метод PATCH, при вызове в следующей строке вы выполните патч:

api.save({age:20},{patch: true, success: function(r,s) { console.log(s); } }); 

// PATCH is invoked