这是我在网上看到如何设置cookie的例子。
require "cgi"
cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC");
cgi = CGI.new("html3")
cgi.out( "cookie" => [cookie] ){
cgi.html{
"\nHTML content here"
}
}
我尝试这样做,然后设置cookie,然后出现一个空白页。
#!/usr/local/bin/ruby
require 'cgi'
load 'inc_game.cgi'
cgi = CGI.new
cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC");
cgi.out( "cookie" => [cookie] ){""}
#see if game submit buttons pressed
doIt = cgi['play']
puts "Content-type: text/html\n\n"
play = Game.new
#welcome
if doIt == ''
puts play.displayGreeting
end
#choose weapon
play.playGame
if doIt == 'Play'
move = cgi['weapon']
human = play.humanMove(move)
computer = play.ComputerMove
print human
print computer
result = play.results(human,computer)
play.displayResults(result)
end
所以我的问题首先是,我错过了什么/做错了什么?其次,我想知道是否有人想要解释什么.out与.header相反或是否存在差异?
谢谢,
列维
答案 0 :(得分:2)
我相信这一行:
cgi.out( "cookie" => [cookie] ){""}
正在刷出你的标题。
在我的TTY中运行代码
Content-Type: text/html Content-Length: 0 Set-Cookie: rubyweb=CustID%3D123&Part%3DABC; path= Content-type: text/html
被发出,“Content-Length:0”(由out {}中的空字符串生成)可能告诉浏览器你已经完成了。
cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC");
cgi.header( "cookie" => [cookie] , type => 'text/html' )
#normal printing here
最好发送标题。
选择'做处理' - '然后考虑输出'模型可能会有所帮助。
require 'cgi'
load 'inc_game.cgi'
cgi = CGI.new
cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC");
output = "";
#see if game submit buttons pressed
doIt = cgi['play']
play = Game.new
#welcome
if doIt == ''
output << play.displayGreeting
end
#choose weapon
play.playGame
if doIt == 'Play'
move = cgi['weapon']
human = play.humanMove(move)
computer = play.ComputerMove
output << human
output << computer
result = play.results(human,computer)
output << play.displayResults(result)
end
cgi.out( "cookie" => [cookie] , type=>"text/html" ){
output;
}