【发布时间】:2020-05-27 22:32:36
【问题描述】:
我正在尝试创建一个烧瓶 Web 应用程序,如果用户第一次访问我的应用程序,他将被引导到一个 index.html 页面,在那里他将被提示输入一个名称并提交它。然后我将名称保存在本地存储中并将用户重定向到第二个 html 页面channels.html。现在如果用户关闭选项卡并第二次访问应用程序,他应该被重定向到第二页channels.html,即"/chanels"路由自动而不是第一页。
这是我目前编写的 app.py python 文件:
@app.route("/")
def index():
return render_template("index.html")
@app.route("/channels", methods=['GET', 'POST'])
def channels():
if request.method == "POST":
name = request.form.get("display_name")
return render_template("channels.html", name=name)
render_template("channels.html")
这是我的 index.html:
<script src="{{url_for('static', filename='index.js')}}"></script>
<h2>Enter your name!</h2>
<form action="/channels" method='Post'>
<input id="displayname" name="display_name" placeholder="Name" autocomplete="off" autofocus required type="text"/>
<input type="submit" id="submitbutton" onclick="store()"/>
</form>
还有 index.js:
function store(){
var name= document.getElementById("displayname");
localStorage.setItem("displayname", name.value);
}
我尝试用谷歌搜索如何做到这一点,但找不到解决方案。
任何帮助将不胜感激。
编辑:根据@AkibRhast 的建议,我尝试检查localStorage 是否存在,如果存在,则重定向到channels.html,因此我将以下代码添加到我的index.js 文件中:
if(localStorage.getItem("displayname")){
window.location.replace("/channels");
}
但是现在每当我访问索引页面时,我都会收到 404 Not Found 错误,尽管 url 栏中的 url 具有指向频道的链接,即 http://127.0.0.1:5000/channels.html。
【问题讨论】:
-
在
channels函数中肯定会检查方法是'Get'而不是'POST'? -
@TylerH,我不太明白你的问题。是的,
channels函数检查方法是 GET 还是 POST.. -
我的意思是,在一个网站中,
POST部分通常会做一些事情,比如根据路径的GET部分的值编辑数据库,这就是为什么在一个表单中方法是@987654339 @不是GET. -
@TylerH,是的,那是真的……但你认为这对我的问题有影响吗?
-
不是专门针对您的问题,但如果您的路线不正确,它可能会导致进一步的问题。但是对于您的问题,您将需要某种
cookie系统,我使用bottle,这是一个不太流行的网络库,对于这样的事情,我会查看cookies。当你第一次到达页面时我会设置一个 cookie 值,说你已经到达它,然后当你返回时,如果它是真的将你重定向到第二个页面。
标签: javascript python html flask local-storage