【问题标题】:Send Json data and redirect using Jquery and node js使用 Jquery 和 node js 发送 Json 数据和重定向
【发布时间】:2018-06-04 19:01:15
【问题描述】:

我有如下页面如下图:

当我单击编辑按钮时,我希望将按钮的 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');});

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

【问题讨论】:

  • 你在redirectContest中得到id吗?
  • 是的,我在 redirectContest 中收到了 id

标签: javascript jquery json node.js redirect


【解决方案1】:

你首先需要修改下面的路由-

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'
    });
});

【讨论】:

  • 感谢您的帮助!您是否也知道为什么当我单击第一个按钮时我得到两个 id,但是当我在控制台登录重定向路由功能时单击第二个按钮时我只得到一个。我收到以下控制台日志。 { id: 'Bqk6QzB7' } { id: 'GL55DSMd' } { id: 'GL55DSMd' }
  • 您还必须将selected recorddata 发送回viewContest 页面。
  • @MUT 是的,我知道,我有不同的方法来填充 viewContest 页面。我感到困惑的是,当我单击表格中的第一个编辑按钮时。它向我的节点 js 服务器发送了两个重复 ID,而不仅仅是一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 2017-06-15
  • 1970-01-01
  • 2016-11-20
  • 1970-01-01
相关资源
最近更新 更多