【问题标题】:AjAX post request trouble redirecting the pageAjAX 发布请求重定向页面时出现问题
【发布时间】:2016-05-02 14:47:14
【问题描述】:

我正在尝试使用 express 重定向到一个关于 AJAX 发布请求成功的不同网页,但我无法弄清楚。

我尝试在服务器端使用res.redirect(),在客户端使用window.location=urllocation.href=urllocation.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....

标签: ajax node.js express pug


【解决方案1】:

服务器代码需要发送新 URL,而不是重定向,然后客户端代码使用该 URL 进行重定向。所以:

服务器代码:

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.json({"redirect":"http:www.google.com"});//replace this with your redirect url
      });
    });
});

和客户端代码:

function addContact(){
  var contactName = $('#name').val();
  var email = $('#email').val();
  var newContact = {name: contactName, email: email};

  $.post('/contacts/add', newContact)
    .success(function(data){
      window.location.href = data.redirect;
    })
}

应该这样做。

【讨论】:

    猜你喜欢
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多