2
2

More than 5 years have passed since last update.

Backbone.js1.2 + FuelPHP1.7 + JSONPを使ってみた備忘録

Posted at

backbone.js(dev1.localhost)からfuelphp+mongodbでつくったrestAPI(dev2.localhost)にリクエストし、jsonpレスポンスをconsole.logに吐き出すサンプルソース

HTML(Backbone.js)

<!DOCTYPE html>
<html lang="ja">
<head>
 <meta charset="UTF-8">
 <title>BackboneJS</title>
 <script src="./jquery.js"></script>
 <script src="./underscore.js"></script>
 <script src="./backbone.js"></script>
 <script>
  var MyModel = Backbone.Model.extend({
      // jsonpへのリクエスト ?callback=と書いてfuelphpのjsonpが返すresponse関数を指定する
      urlRoot: 'http://dev2.localhost/example/example.jsonp?callback=response', 
     // jsonpする場合
   sync: function(method, model, options) {
    var params = _.extend({
      type:         'GET',
      dataType:     'jsonp',
      url:   model.url() + '&example=' + model.get('example'),
      processData:  false
    }, options);

    return $.ajax(params);
   },
   parse: function(response) {
    if (response) {
     if (response.success) {
      return {data: response};
     }
    }
   }
  });

  var myModel = new MyModel({example: "123222222"});
  myModel
      .fetch()
      .success(function(response) {
          console.log(response);
      });
 </script>
</head>
<body>

</body>
</html>

fuelphp

fuel/app/class/controller/example.php
<?php
class Controller_Example extends Controller_Rest
{
  public function get_example()
  {
    $example = Input::get('example');
    $test = 'test';

    $this->response(array(
          'example' => $example,
          'test' => $test,
          ));
  }
}

仮に1年後に使うことになっても思い出せるようメモメモ^^;

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2