AjAX发布请求无法重定向页面

时间:2016-01-26 04:27:53

标签: ajax node.js express pug

我尝试使用快递重定向到AJAX发布请求成功的不同网页,但我无法弄清楚。

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

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

服务器代码需要发送新的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;
    })
}

应该这样做。

相关问题