【发布时间】:2017-11-23 17:59:45
【问题描述】:
假设我的渲染 HTML 有这条路线:
app.get('/profile/:id', function (req, res) { // my route
res.render('profile', { id: Number(req.params.id) }); // render the file and set a variable
});
在我的个人资料页面的客户端 javascript 文件中,我想从服务器获取数据。我在加载页面时通过向服务器发送用户 ID 来请求数据,服务器返回一个用户对象:
$(document).ready(function() {
var user = null;
$.ajax({
type: 'GET',
url: '', // This one is missing here
dataType: 'json'
}).done(function(data){
user = JSON.stringify(data);
});
console.log(user.name);
});
我的服务器会处理这个功能:
app.get('', function (req, res) { // missing route
var userId = ; // This is missing
var userObj = getUserById(userId);
res.send(userObj);
});
我必须使用什么路线?教程说我必须通过/profile/:id这样的路由但是这个路由已经存在了?
我尝试定义一条新路线,例如:
app.get('/reqUser/:id', function (req, res) { // Ajax route
res.send(getUserById(Number(req.params.id)));
});
对于我的 Ajax 调用,我传入了 url http://localhost:8888/reqUser/12345 但这似乎是错误的,因为在使用 Ajax 调用后用户仍然为空。
那么如何定义处理页面和 Ajax 调用的路由呢?
【问题讨论】:
-
ajax 输出和页面渲染有什么区别?不太清楚你想在这里完成什么
-
user 仍然是 null 所以我认为我的 Ajax 调用是错误的
标签: javascript jquery node.js ajax express