0

필립 스터 전 (Phil Sturgeon)이 쓴 나머지 라이브러리를 사용하기 시작했습니다. 몇 가지 간단한 예제를 작성하여 사용하기 시작했습니다. 나는 '게시'와 '가져 오기'작업을하지 못하고 넣고 지우지 않습니다. 아래 코드를 기반으로 몇 가지 질문이 있습니다. 내 CI의 REST 컨트롤러 내가 모델을 저장하거나 모델을 가져올 때 기본적으로 컨트롤러에서 Get 포스트가 호출됩니다백본에서 코드 서명자 문제 해결

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() 
    { 

    } 
} 

에서

// 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 

. 모델에 지정된 id를 사용하여 model.save() 및 model.destroy()를 사용하여 서버에 대한 put 또는 delete 요청을 할 수 있습니다. 그러나 서버 오류가 있습니다. index_put 또는 index_delete를 호출 할 수없는 것 같습니다. 누군가가 내가 처리 할 수있는 방법을 알고 않습니다 컨트롤러의

  • 삭제 요청은
  • 이 ID로 하나의 레코드가 자식에서
  • 을 지정받을 컨트롤러에서

    1. 넣어 요청을 난 단지 보았다 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?

    이 간단한 해결책은 다음과 백본 라인 1191의 methodMap을 변경하는 것입니다 : 당신은이 스택 오버 플로우 문제를보고 할 수 있습니다

    // 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(); 
    
    를 다음을 수행 다음과 같은 방법을 가지고 당신이 컨트롤러가 REST_Controller을 확장 사람이라는 클래스 person.php라고 했어야 application/controllers 폴더에

    :

    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; 
    

    에 다음 줄을 추가, 나는 간단한 모델을 생성하고 여기에 결과가 applications/controllers 폴더라는 API 컨트롤러를 필요

    이 있습니다 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라는 모델을 생성

    나는 패치하는 법을 모르지만 이것이 도움이되기를 바랍니다.

    편집

    나는 코드 점화기의 REST 구현에 포함되지 않은 패치를 수행하는 방법을 발견했다. REST_Controller 라인 (39)에서는

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

    당신이 그 일을 한 후,

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

    또한 당신을이 코드를 추가, 또한,이 방법을 적용, 마지막에 'patch'를 추가 할 필요가 다음을 찾을 수 있습니다 패치 인수를 구문 분석하려면 다음 코드를 추가해야합니다 : 당신이를 호출 할 때 백본 문서에 따르면, 지금

    /** 
    * 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}을 통과해야 다음 줄을 따라 패치를 실행하십시오 :

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