简体   繁体   中英

Backbone JS and CodeIgniter REST Server

I have a standard CI web app, but I've decided to get the chaotic javascript in order using backbone. I had a whole pile of serialized forms/jQuery AJAX requests to various controller methods: authenticate, change_password, register_member, request_new_password, etc.., and don't quite understand how REST works instead. I'm using Phil Sturgeon's REST library for CI https://github.com/philsturgeon/codeigniter-restserver

Should every backbone model have a different api url? And what am I supposed to actually call the controller methods?

<?php  
    require(APPPATH.'/libraries/REST_Controller.php');  
    class RestApi extends REST_Controller  
    {  
        function get()  
        {  

But it just 404s.

I just don't get how to replace the routing to fifty of my old methods based on a handful of HTTP methods. Does the name of the backbone model need to match something on the server side?

You have to name your functions index_HTTPMETHOD. In your example it would be:

class RestApi extends REST_Controller {
    // this will handle GET http://.../RestApi
    function index_get() {
    }

    // additionally this will handle POST http://.../RestApi
    function index_post() {
    }
    // and so forth

    // if you want to POST to http://.../RestApi/somefunc
    function somefunc_post() {
    }

}

the url -attribute of the model should match the server-side 'url' which returns the JSON that will make up the model's attributes. Backbone.js has default functionality to this, which is to match the model's collection url with it's id attribute. The collection url requirement can be foregone by overriding the urlRoot -function, in order to operate model's outside of collections.

If you want to be independent of the id -attribute as well, you sould override the url -attribute/function to provide your own url that matches to the model on the server, like this:

url: 'path/to/my/model'

or

url: function() { // Define the url as a function of some model properties
  var path = this.model_root + '/' + 'some_other_url_fragment/' + this.chosen_model_identifier;
  return path; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM