我正在使用 HTML、JQuery 和 NodeJS。我的问题是我正在尝试将表单从 index.html 发布到 Node 、进程(数据库等),用 JSON 响应到 JQuery 并重定向。所以我想处理 json 响应并在不同的 HTML 页面 (board.html) 上查看它。
为此,我试图在两个 HTML 页面(index.html、board.html)上包含相同的 JS 文件,我从索引中发布了有效的数据,但在重定向到 board.html 之后,JS 没有加载board.html 上的内容:
我试过了
window.location.replace("/views/board.html");
$('#b-content').append("content...").after('topic: '+res.topic);
//index.js
$(document).ready(function() {
console.log("READY!")
$("form").submit(function(e) {
$(this).attr('action', 'api/board/:b')
$.ajax({
url: '/api/board/:b',
type: 'post',
dataType: 'json',
data: $('#main-form').serialize(),
success: function(res) {
window.location.replace("/views/board.html");
$('#b-content').append("content...").after('topic: '+res.topic);
$('#responses').append("topic: <h3>" + res.topic + "</h3>");
}
});
// e.preventDefault();
});
});
//后端
app.route('/api/board/:b')
.post(function(req, res) {
compiledObject = {
board: req.body.board,
user: req.body.name,
topic: req.body.topic,
thread: req.body.thread
};
res.json(compiledObject);
})
//index.html 示例
<body>
<header>
<h1>
Anon Message Board
</h1>
</header>
<div id="form-div">
<form id="main-form" method="post" action="">
username:
<input type="text" placeholder="coolname" name="name"/><br>
<label for="general">General</label>
<input type="radio" name="topic" value="general"></span>
<label for="tech">Tech</label>
<input type="radio" name="topic" value="tech"><br>
board:
<input type="text" name="board" /><br>
message:
<textarea name="thread" ></textarea><br><br>
<input type="submit" value="submit"/>
</form>
</div>
<div id="responses">
<p id="res-name"></p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="views/index.js"></script>
</body>
//board.html 示例
<body>
<h1>Board:</h1>
<div id="b-content">
<p>content ...</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="/views/index.js"></script>
</body>
....
我可以加载 board.html,但未加载附加元素。
最佳答案
一旦触发:
window.location.replace("/views/board.html");
您正在从您的服务器请求一个新页面,因此您在索引页面上完成的所有逻辑都消失了。在重定向之前,您需要将从索引页面收到的数据存储在 LocalStorage
或 cookie
中。
所以你的逻辑应该是这样的
get data
listen for error
if error dont redirect and tell user
if no error, store the data you received, then redirect to new page
load data into your new page
您可能还需要考虑您的应用究竟在做什么以及流程是如何运作的。每次用户发布消息时,您是否应该重定向到新页面?
关于javascript - GET 请求到不同的 HTML 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57861978/