【发布时间】:2016-05-02 14:47:14
【问题描述】:
我正在尝试使用 express 重定向到一个关于 AJAX 发布请求成功的不同网页,但我无法弄清楚。
我尝试在服务器端使用res.redirect(),在客户端使用window.location=url 和location.href=url 和location.replace(url),但这些都不适合我。
这是我的 jQuery ajax 请求:
function addContact(){
var contactName = $('#name').val();
var email = $('#email').val();
var newContact = {name: contactName, email: email};
$.post('/contacts/add', newContact)
.success(function(data){
location.href = data.redirect;
})
}
这是我的服务器代码:
router.post('/add', function(req, res, next){
fs.readFile('./contacts.json', function(err, data){
if (err) return res.status(400).send(err);
var contactArr = JSON.parse(data);
var newContact = req.body;
contactArr.push(newContact);
fs.writeFile('./contacts.json', JSON.stringify(contactArr), function(err){
if (err) return res.status(400).send(err);
res.redirect('/');
});
});
});
任何帮助将不胜感激!
【问题讨论】:
-
那么服务器应该返回 url....