最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用Jquery和节点js发送Json数据和重定向

运维笔记admin8浏览0评论

使用Jquery和节点js发送Json数据和重定向

使用Jquery和节点js发送Json数据和重定向

我有以下页面如下所示:

当我点击编辑按钮时,我希望将按钮的id发送到我的节点JS服务器,它将我重定向到以下网页:

此外,我的Node JS服务器将发送回JSON数据以填充下一页中的表单。我面临的问题是,每当我点击按钮时,我的页面都不会被重定向。以下jquery代码发送ajax调用:

$("#viewAllContest button").click(function () {
//console.log($(this).attr('id'));
var id = $(this).attr('id');
$.ajax({
    type: 'POST',
    url: '/contests/redirectContest',
    data: JSON.stringify({id:id}),
    success: function(data) { console.log('success')},
    contentType: "application/json",
    dataType: 'json'
    });
});

然后我在Node JS应用程序中的路由接收请求并应重定向页面:

router.post('/redirectContest',function (req,res) {
var id = req.body.id;
console.log(id);
res.redirect('/contests/viewContest');});

我甚至添加了return res.redirect('/contests/viewContest');但它没有重定向我的网页。呈现viewContest的代码是:

router.get('/viewContest',ensureAuthenticated,function (req,res) {

res.render('viewContest');});

如果有人能指导我在这里出错,我将不胜感激。

回答如下:

您首先需要修改以下路线 -

router.post('/redirectContest',function (req,res) {
var id = req.body.id;
console.log(id);
//remove the redirect code
//res.redirect('/contests/viewContest');});
//Now send the json response 
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ url: '/contests/viewContest' }));

现在修改你的ajax代码如下 -

$("#viewAllContest button").click(function () {
//console.log($(this).attr('id'));
var id = $(this).attr('id');
$.ajax({
    type: 'POST',
    url: '/contests/redirectContest',
    data: JSON.stringify({id:id}),
    success: function(data) { window.location.href=data.url;},
    contentType: "application/json",
    dataType: 'json'
    });
});
发布评论

评论列表(0)

  1. 暂无评论