【问题标题】:Redirect to new page after AJAX post request using express使用 express 进行 AJAX 发布请求后重定向到新页面
【发布时间】:2017-07-15 18:25:50
【问题描述】:

我需要制作一个按钮,点击后将我重定向到一个新页面(localhost:1337/LEDon)并将一些数据记录到控制台。但是,我无法单击按钮来加载新页面。

这是我的代码 -

app.js

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.sendFile(__dirname + '/view.html');
});

app.post('/LEDon', function(req, res) {
  console.log('LEDon button pressed!');
  res.sendFile(__dirname + '/success.html');
});

app.listen(1337);

clientside.js

$('#ledon-button').click(function() {
    $.ajax({
        type: 'POST',
        url: 'http://localhost:1337/LEDon'
    });
});

view.html

<!DOCTYPE html>
<head>
</head>

<body>
    <button id='ledon-button'>LED on</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src='clientside.js'></script>
</body>
</html>

success.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Success page</title>
  </head>
  <body>
    LEDon button pressed!!
  </body>
</html>

【问题讨论】:

  • 有几种方法可以做到这一点,但如果代码和你在这里一样简单,你可以为你的 ajax 调用做一个 success: 函数并将 window.location 设置为你的 URL我喜欢

标签: javascript ajax express


【解决方案1】:
$.ajax({
        type: 'POST',
        url: 'http://localhost:1337/LEDon',
        success:function(data, code, jqXHR) {
            window.location.pathname = "success.html"
        }
});

和你的节点:

app.post('/LEDon', function(req, res) {
  console.log('LEDon button pressed!');
  res.status(200)
  res.sendFile(__dirname + '/success.html');
  res.end()
});

这是一种实现方式,前提是这是您想要的唯一功能。否则你可以发送一个 3XX HTML 状态码,我相信浏览器会为你处理它

【讨论】:

  • 所以,我这样做了,现在它记录了“按下 LEDon 按钮”,但它不会呈现 success.html 页面。它也给了我这个错误 - jquery.min.js:4 POST http://localhost:1337/LEDon net::ERR_CONNECTION_REFUSED。另外,您能否添加一个发送 3XX HTML 状态代码的示例,因为我肯定需要额外的功能。
  • 糟糕,抱歉,我误读了您的问题,我以为您试图拉出该页面。只需将 window.location.pathname 更改为 success.html。
  • 另外,您为什么使用 sendFile 来传递您的 HTML 内容?我会使用 res.render(file.html)。 sendFile 用于当您明确告诉客户端获取该文件时。
  • 我将window.location.pathname = "../success.html" 替换为clientside.js 放在assets 文件夹中。还是一样的问题。
  • 啊,我以为你已经写了 success.html 路由!很高兴你明白了。
猜你喜欢
  • 1970-01-01
  • 2018-09-11
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-18
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多