Backbone.js使用jsonp api示例

MyModel = Backbone.Model.extend({
    url: function() { 
        return '/yourJsonpUrlhere';
    },

    // override backbone synch to force a jsonp call
    sync: function(method, model, options) {
        // Default JSON-request options.
        var params = _.extend({
          type:         'GET',
          dataType:     'jsonp',
          url:            model.url()+"?callback=?",
          processData:  false
        }, options);

        // Make the request.
        return $.ajax(params);
    },

    parse: function(response) {
        // parse can be invoked for fetch and save, in case of save it can be undefined so check before using 
        if (response) {
            if (response.success ) {
                                // here you write code to parse the model data returned and return it as a js object 
                                // of attributeName: attributeValue
                                
                return {name: response.name};      // just an example,                
            } 
        }
    }
});

 

sync: function(method, model, options) {             
        options.dataType = 'jsonp';
        options.url="http://localhost:8084/CrossDomain_backbone/messages.json?callback=?";           
        //options.contentType='application/json-p';
        options.error=this.errorr;
        return Backbone.sync(method, model, options);
    }
   ,
    parse: function(resp){
        alert('inside parse..');
        return resp.model;
    },
    errorr:function(response,responseText)
    {
        alert('inside callback..: ' + responseText);
    },
$(function () {
   var Job = Backbone.Model.extend({
      defaults:{
         displayName:'not set'
      }
   });

   var AppView = Backbone.View.extend({
      el:$("#hudApp"),

      initialize:function () {
         var job = new Job;
         job.url = 'https://jenkins.example.com/jenkins/job/test-job/api/json/?jsonp=?';
         job.fetch({dataType:"jsonp"});

         alert(job.get('displayName'));
      });
   });

   var app = new AppView;
});
posted on 2012-11-28 23:03  稻草人.Net  阅读(1950)  评论(1编辑  收藏  举报