简体   繁体   English

将JSON数据从Express发送到Backbone

[英]Sending JSON data from Express to Backbone

I made a simple Backbone app and I'm trying to use JSON data from a MYSQL database with an Express server. 我制作了一个简单的Backbone应用程序,并试图在Express服务器上使用MYSQL数据库中的JSON数据。 When I send a GET request with Express to send data to Backbone, the html template from backbone disapear, there's only the JSON array on the screen. 当我使用Express发送GET请求以将数据发送到Backbone时,主干的html模板消失了,屏幕上只有JSON数组。 How can I get the data in my html/underscore template ? 如何在html /下划线模板中获取数据?

server.js (Express) server.js(快速)

 var express = require('express'); var bodyParser = require('body-parser'); var mysql = require('mysql'); var app = express(); app.use(express.static(__dirname + '/public')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); var connection = mysql.createConnection({ host: 'localhost', user: '***', password: '***', database: '***' }); connection.connect(); app.get('/users', function(req, res) { connection.query('SELECT * FROM users', function(err, result) { if (err) { console.error(err); return; } res.json(result); }); }); app.get('/users/:id', function(req, res) { connection.query('SELECT * FROM users WHERE id =' + connection.escape(req.params.id), function(err, result) { if (err) { console.error(err); return; } res.json(result); }); }); app.get('*', function(req, res) { res.sendFile(__dirname + '/public/index.html'); }); app.listen(8080); 

app.js (Backbone) app.js(骨干网)

 var User = Backbone.Model.extend({ default: { id: 0, name: 'UserName', age: 0 } }) var Users = Backbone.Collection.extend({ model: User, url: '/users' }) var UserView = Backbone.View.extend({ template: _.template($('#UserViewTemplate').html()), tagName: 'li', render: function() { this.el.innerHTML = this.template(this.model.toJSON()) return this; } }); var UsersView = Backbone.View.extend({ template: _.template($('#UsersViewTemplate').html()), tagName: 'ul', render: function() { this.el.innerHTML = this.template(this.collection); this.collection.each(function(user) { var userView = new UserView({ model: user }); this.$el.append(userView.render().el); }, this) return this; } }); var UserRouter = Backbone.Router.extend({ routes: { 'users': 'list' }, list: function() { console.log('list function called') var usersView = new UsersView({ collection: users }) $('body').append(usersView.render().el); } }) var users = new Users(); users.fetch().then(function() { var router = new UserRouter(); Backbone.history.start({pushState: true}); }); 

Fixed it ! 修复 ! I just had to use the route localhost:3000/#users , not localhost:3000/users. 我只需要使用路由localhost:3000 /#users ,而不是localhost:3000 / users。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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