【问题标题】:Webpage redirect to the main page with CGI Python使用 CGI Python 将网页重定向到主页
【发布时间】:2011-09-01 15:38:09
【问题描述】:

作为我的第一个网络应用程序,我开发了一个非常简单的调查。每当页面刷新时,都会向用户提出随机问题。使用 post 将答案发送到 cgi 脚本以将答案保存到数据库中。

但是,当用户按下提交按钮时,它会自动转到负责处理数据的页面,并且由于它没有任何输出,因此它是一个空白页面。现在,如果用户想要回答另一个问题,他们必须在浏览器中按“返回”并刷新页面,以便弹出一个新问题。我不想要这个。

我希望当用户按下提交时,答案会自动转到处理脚本,并且页面会用新问题自行刷新,或者至少在处理后会重定向到包含新问题的主调查页面。

【问题讨论】:

  • meta http-equiv="refresh" content="0;url=http://example.com/"> 不是一个选项?
  • @Khachik:我应该把它放在哪里?在标题中?
  • 页面加载后一直刷新。周围有吗?

标签: python html forms cgi


【解决方案1】:

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

这比听起来要简单得多。接收 POST 的 CGI 脚本必须简单地产生以下输出:

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

【讨论】:

  • 在哪里打印这些输出?
  • 虽然这在我桌面上的 Chrome 中运行良好,但在我的 ipad 上却出现 safari 错误,说“重定向太多”......有什么想法吗?我尝试清空 ipad 上的缓存.. 但没有运气。
【解决方案2】:

您还可以从处理脚本中发送 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>'

【讨论】:

  • 你能不能给我一个更详细的例子,我是全新的。不知道把这个放在哪里。thx
【解决方案3】:
<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 缺点和替代方案here

【讨论】:

  • 我做到了,但是我的页面在加载后一直刷新...我希望在表单提交后刷新一次。它在我按下提交按钮之前就刷新了。
  • @Hossain,您可能会重定向到一个页面,该页面也包含该元数据。
  • 是的,问题正在主页中提出。提交后,我希望此主页再次刷新(导致弹出新问题)
猜你喜欢
  • 1970-01-01
  • 2016-10-18
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 2011-05-24
  • 2018-02-08
  • 1970-01-01
相关资源
最近更新 更多