【问题标题】:e.preventDefault(); not working with httpse.preventDefault();不使用 https
【发布时间】:2021-12-10 01:31:21
【问题描述】:

我正在使用 bluehost 来托管通过 node.js 中的 express 提供的网页

var app = express();
app.listen(80);

您可以使用 HTTP 的 80 端口或 https 的 443 端口导航到该页面。本质上,我只是在页面 URL 之前手动输入 HTTP 或 https 来控制它。

我在 ejs 页面中有一个表单,jquery 等待表单提交,当它提交时,我使用 e.preventDefault() 来阻止页面重新加载,然后使用 ajax 将此表单数据发送到节点服务器。然后,ejs 页面有一些看起来不错的 CSS 转换,而我希望节点服务器响应并运行成功函数。这适用于本地以及使用 HTTP 托管页面时。如果我使用 https 连接,表单数据实际上并没有传递到服务器(它在提交表单时 console.log 在服务器端的一些信息)并且页面只是刷新。导致这种不同行为的问题可能是什么?

感谢任何帮助

编辑:

这是表单的客户端代码,它不应该允许页面刷新,但在 https 上连接时会刷新而不是发布。

<form id="sendmessageform" name="sendmessageform">
  <input type="text" name="logcustomername" placeholder="Customer Name" id="logcustomername" autocomplete="off">
  <input type="tel" name="logcustomernumber"  placeholder="Customer Phone Number" id="logcustomernumber" autocomplete="off">
  <input type="text" name="logstorename"  placeholder="Store Name" id="logstorename" autocomplete="off">
  <input type="submit" value="Submit"/>
</form>

<script>
$('#sendmessageform').submit(function(e){
    e.preventDefault();
    $.ajax({
        url: '/submit',
        type: 'post',
        data:$('#sendmessageform').serialize(),
        success:function(data){
          console.log(data)
        }
    });
});
</script>

以及这条路由的服务器端

app.post('/submit',
  function(req, res){
    console.log(req.body)

    var temp = new Object();
    temp["statustype"] = "pass";
    temp["content"] = "message contents.";
    
    // return a temporary json object to the client
    res.send(temp);
  });

编辑2:

我尝试将 e.preventDefault() 更改为 e.stopImmediatePropagation(),即使在 https 上单击提交按钮时,页面也不再刷新。我现在唯一的问题是,当我在 HTTP 上连接时,表单已提交并且服务器控制台记录表单数据,但是当我在 https 上连接时没有任何反应。好像 ajax 甚至没有尝试发布表单。

【问题讨论】:

  • 请显示您遇到问题的特定客户端代码,最好向我们显示实时 URL 是什么,以便我们可以实际尝试/调试。根据您有限的描述,我们不太可能知道该建议什么。另外,请为您的服务器端代码显示app.post() 处理程序。如果客户端页面重新加载,听起来您在提交表单时没有成功阻止默认页面操作。

标签: jquery css node.js https


【解决方案1】:

看起来这是一个简单的错误。我尝试在 jquery 函数的顶部添加一个 alert("Test") 框,但单击按钮时没有弹出,这告诉我这不是表单本身的问题,而是 jquery 本身不想跑。查看我的标头,我使用 HTTP 而不是 https 引用 jquery 源,所以当我使用 https 连接时,我的浏览器给出了一个错误,这是不允许的。将源 URL 更改为 https:// 完全解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2022-01-23
    • 2014-05-27
    • 2019-10-26
    相关资源
    最近更新 更多