html 为什么这段代码不能呈现正确的东西?

9cbw7uwe  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(118)

我有这样的代码,用于将用户重定向到Python flask中的不同子页面:

@app.route('/')
def main():
    return render_template('interface.html')

@app.route('/#ordergrade/')
def ordergrade():
    return sort.orderbygrade(True, False).to_html()

字符串
interface.html的代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>xxxxxxxxxxxxxx</title>
  </head>
  <body>
    <h1>Options</h1>
    <p>Click on the buttons below to be redirected to a web page.</p>
    <button onclick="window.location.hash='#ordergrade/'">1</button>
    <button onclick="window.location.hash='#orderuniversity/'">2</button>
    <button onclick="window.location.hash='#showopts/'">3</button>
    <button onclick="window.location.hash='#delete/'">4</button>
    <button onclick="window.location.hash='#infnum/'">5</button>
    <button onclick="window.location.hash='#supnum/'">6</button>
  </body>
</html>


当点击第一个按钮时,我被正确地重定向到/#ordergrade页面,但只有interface.html被渲染。为什么会发生这种情况?
一切似乎都很顺利,除了什么也没发生。

vvppvyoh

vvppvyoh1#

URL的fragment#之后的部分)不会发送到服务器,因此当您访问路径/#ordergrade/时,服务器只能看到/
如果你想在URL中使用#,你需要使用URL encoding进行编码,例如,

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index_view():
    # Here, `%23` represents "#"
    return '<a href="/%23test/">test</a>'

@app.route("/#test/")
def test_view():
    return "worked!"

字符串
也可以在客户端处理,看看浏览器/JavaScript hashchange事件,或者考虑使用包含路由解决方案的前端javascript框架。

相关问题