网页通过CGI Python重定向到主页

8 投票
3 回答
27773 浏览
提问于 2025-04-16 18:18

我开发了一个非常简单的调查问卷,这是我做的第一个网页应用。每次页面刷新时,系统会随机问用户一些问题。用户的回答会通过一种叫做POST的方法发送给一个cgi脚本,这个脚本负责把答案保存到数据库里。

但是,当用户按下提交按钮后,页面会自动跳转到处理数据的页面,而这个页面没有任何内容,所以用户看到的是一个空白页。如果用户想回答下一个问题,就得点击浏览器的“返回”按钮,然后刷新页面,这样才能出现新的问题。我不想这样。

我希望用户按下提交后,答案能自动发送到处理脚本,然后页面能自己刷新,显示一个新问题。或者至少在处理完后,能跳转回主调查页面,并显示一个新问题。

3 个回答

1
<html> 
  <head> 
    <meta http-equiv="refresh" content="0;url=http://www.example.com" /> 
    <title>You are going to be redirected</title> 
  </head> 
  <body> 
    Redirecting...
  </body> 
</html>

查看 meta-refresh 的缺点和替代方案,可以点击 这里

8

你还可以从你的处理脚本中发送一个HTTP头信息:

Location: /

在你处理完答案后,就可以发送上面的头信息。我建议你在后面加上一个随机数字的查询字符串。比如,下面是一个Python的例子(假设你在使用Python的CGI模块):

#!/usr/bin/env python
import cgitb
import random
import YourFormProcessor

cgitb.enable() # Will catch tracebacks and errors for you. Comment it out if you no-longer need it.

if __name__ == '__main__':
  YourFormProcessor.Process_Form() # This is your logic to process the form.

  redirectURL = "/?r=%s" % random.randint(0,100000000)

  print 'Content-Type: text/html'
  print 'Location: %s' % redirectURL
  print # HTTP says you have to have a blank line between headers and content
  print '<html>'
  print '  <head>'
  print '    <meta http-equiv="refresh" content="0;url=%s" />' % redirectURL
  print '    <title>You are going to be redirected</title>'
  print '  </head>' 
  print '  <body>'
  print '    Redirecting... <a href="%s">Click here if you are not redirected</a>' % redirectURL
  print '  </body>'
  print '</html>'
10

你想要实现这个功能:https://en.wikipedia.org/wiki/Post/Redirect/Get

其实这比听起来要简单得多。接收POST请求的CGI脚本只需要输出以下内容:

Status: 303 See other
Location: http://lalala.com/themainpage

撰写回答