使用CGI Python将网页重定向到主页面

Hos*_*ein 5 html python forms cgi

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

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

我想要的方式是,当用户按下提交时,答案会自动转到处理脚本,页面会自动刷新一个新问题,或者至少在处理后,它会重新定向到主要调查页面并显示新问题.

pob*_*obk 7

您还可以从处理脚本发送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>'
Run Code Online (Sandbox Code Playgroud)


小智 6

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

它比听起来简单得多.接收POST的CGI脚本必须只生成以下输出:

Status: 303 See other
Location: http://lalala.com/themainpage
Run Code Online (Sandbox Code Playgroud)