Я столкнулся с такой же точной проблемой, похоже, что методы 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
Кто-нибудь может мне помочь? – eded