Asked By: Anonymous
I’m new to Backbone.js framework,in my application i need to call node to js express route from Backbone using Ajax.How can i do that.In jquery i’m doing ajax call to express route using below code.How to do this in Backbone.
In jquery
$.ajax({
url: 'http://localhost:8080/index.html',
dataType: "json",
cache: false,
success: function(data) {
alert('success '+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
app.js
var express=require('express');
var app=express();
app.use(express.bodyParser());
app.use(express.static(__dirname + '/public'));
app.get('index.html',function(req,res){
res.json({a:"A",b:'B',c:'C'});
});
app.listen(8080);
Solution
Answered By: Anonymous
Backbone communicate with server by “Model” and “Collection”, and it assume your server is RESTful. In your case I think you want get some json data from server for page initialization. so, my advise is:
1, Define a Backbone Model, set it’s url as ‘index.html’
2, Create a instance of this Model in the process of page initialization.
3, Call fetch() method on this instance, this will cause the server send the raw data to the page, and model instance will be populate by the raw data.
4, Define your Backbone View, and use the model above to render it.
this is a little abstract, read the backbone official documents is strongly recommended.