Ruby 內建 cgi 函式庫支援 CGI 程式設計。本文從最基本的 CGI 腳本、表單參數存取、CGI 物件方法、HTML 標籤產生方法完整介紹。
#!/usr/bin/ruby
puts "HTTP/1.0 200 OK"
puts "Content-type: text/html\n\n"
puts "This is a test"
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
puts cgi.header
puts "This is a test"
# 單一值
cgi['FirstName'] # => ["Zara"]
# 所有參數 Hash
params = cgi.params # => {"FirstName"=>["Zara"], "LastName"=>["Ali"]}
params['FirstName'] # => ["Zara"]
# 所有鍵
cgi.keys # => ["FirstName", "LastName"]
cgi['name'] # => "Zara" (第一個)
cgi.params['name'] # => ["Zara", "Huma", "Nuha"]
require "cgi"
cgi = CGI.new("html4")
cgi.out {
cgi.html {
cgi.head { "\n" + cgi.title{"This Is a Test"} } +
cgi.body {
"\n" + cgi.form {
"\n" + cgi.hr + cgi.h1 { "A Form: " } +
"\n" + cgi.textarea("get_text") + "\n" +
cgi.br + cgi.submit
}
}
}
}
Content-Type: text/html
Content-Length: 302
This Is a Test
部署提示: 腳本需具執行權限(chmod +x),放置於伺服器 cgi-bin 目錄,並確認 Apache/Nginx 啟用 CGI 支援。