背景:使用express框架,前端给后端传数据,后端接受数据跳转新页面加载并渲染。
解决方法:
1、前端使用form直接post,因为ajax并不是为了跳转页面设计的(我不确定具体是不是这个原因),如果使用ajax post数据的话后端接受之后无法render view。
// express框架前端是jade格式
a(href='javascript:void(0);', onclick="document.getElementById('back-home-form').submit();") Home
form#back-home-form(method='post', action="/back_channels")
input#back-home(type='hidden', name='username')
因为username为动态加载,因此JS代码如下:
var back_home = function(){
var input = document.getElementById("back-home");
input.setAttribute('value', username);
};
$(document).ready(function(){
back_home();
};
2、后台部分,首先在server.js中加入post方法,并且为了parse post的数据,还需要使用bodyparser库
// for parsing application/json
app.use(bodyParser.json()