Create an API. php file with the following content:
header('Content-Type: application/json; charset=utf-8');die(json_encode(array('name'=>'tom')));
Create an index.html file. (Based on jquery and underscore, backbone uses mustache for template parsing. Of course, other haml, Jade, or templates in underscore are also supported)
Content:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML> <HEAD> <TITLE> New Document </TITLE><script type="text/javascript" src="./jquery.min.js"></script><script type="text/javascript" src="./underscore.min.js"></script><script type="text/javascript" src="./backbone.min.js"></script><script type="text/javascript" src="./mustache.min.js"></script><script type="text/javascript" src="./custom.js"></script> </HEAD> <BODY> <script id="hello-container-template" type="text/template">
<div>{{name}} says: {{message}} </div>
</script>
</BODY></HTML>
Create a custom. js file with the following content:
// This is a global class var app that manages views, controls, and models ={ models :{}, views :{}, controllers :{}, collections :{}, initialize: function () {new app. controllers. routes (); backbone. history. start () // All backbone programs to be driven, backbone. history. start () is required. }; App. Models. Hello = backbone. model. Extend ({URL: function () {return '/API. php'; // The background address for obtaining data. }, Initialize: function () {This. Set ({'message': 'Hello world'}); // The frontend defines a message field, which is provided by the backend. }); App. views. hello = backbone. view. extend ({El: $ ("body"), template: $ ("# Hello-container-template" ..html (), initialize: function (options) {This. options = options; this. BIND ('change', this. render); this. model = This. options. model;}, render: function () {// render method, with only two targets: Fill this. el, return this for chained operation. Certificate (this.el).html (mustache. to_html ($ (this. el ). template, this. model. tojson (); return this}); app. controllers. routes = backbone. controller. extend ({routes :{"! /Hello ":" hello ", // use #! /Hello driver route}, hello: function () {// create a new model. After the model successfully sends an update request to the backend, it renders the new page var hellomodel = new app based on the model. models. hello; hellomodel. fetch ({success: function (model) {var helloview = new app. views. hello ({model: Model}); helloview. trigger ('change') ;}})}); app. initialize ();