Table of Contents
Zara Ali/A Sweet & Sour Girl
Home Backend Development Python Tutorial 简单介绍Ruby中的CGI编程

简单介绍Ruby中的CGI编程

Jun 10, 2016 pm 03:15 PM
ruby

Ruby 是一门通用的语言,不仅仅是一门应用于WEB开发的语言,但 Ruby 在WEB应用及WEB工具中的开发是最常见的。

使用Ruby您不仅可以编写自己的SMTP服务器,FTP程序,或Ruby Web服务器,而且还可以使用Ruby进行CGI编程。

接下来,让我们花点时间来学校Ruby的CGI编辑。
编写 CGI 脚本

最脚本的 Ruby CGI 代码如下所示:

#!/usr/bin/ruby puts "HTTP/1.0 200 OK" puts "Content-type: text/html\n\n" puts "This is a test"

你可以将该代码保持到 test.cgi 文件中,上次到服务器并赋予足够权限,即可作为 CGI 脚本执行。

如果你站的的地址为http://www.example.com/ ,即可用过http://www.example.com/test.cgi 访问该程序,输出结果为: "This is a test."。

浏览器访问该网址后,Web 服务器会在站点目录下找到 test.cgi文件,然后通过Ruby解析器来解析脚本代码并访问HTML文档。
使用 cgi.rb

Ruby 可以调用 CGI 库来编写更复杂的CGI脚本。

以下代码调用了 CGI 库来创建一个脚本的CGI脚本。

#!/usr/bin/ruby
 
require 'cgi'
 
cgi = CGI.new
puts cgi.header
puts "<html><body>This is a test</body></html>"
Copy after login

以下代码中,创建了CGI 对象并打印头部信息。
表单处理

使用CGI库可以通过两种方式获取表单提交(或URL中的参数)的数据, 例如URL:/cgi-bin/test.cgi?FirstName=Zara&LastName=Ali。

你可以使用 CGI#[] 来直接获取参数FirstName和LastName:

#!/usr/bin/ruby
 
require 'cgi'
cgi = CGI.new
cgi['FirstName'] # => ["Zara"]
cgi['LastName'] # => ["Ali"]
Copy after login

另外一种获取表单数据的方法:

#!/usr/bin/ruby
 
require 'cgi'
cgi = CGI.new
h = cgi.params # => {"FirstName"=>["Zara"],"LastName"=>["Ali"]}
h['FirstName'] # => ["Zara"]
h['LastName']  # => ["Ali"]
Copy after login

以下代码用于检索所有的键值:

#!/usr/bin/ruby
 
require 'cgi'
cgi = CGI.new
cgi.keys     # => ["FirstName", "LastName"]
Copy after login

如果表单包含了多个相同名称的字段,则该相同字段的值将保存在数组中。

以下实例中,指定表单中三个相同的字段"name",值分别为 "Zara", "Huma" 和 "Nuha":

#!/usr/bin/ruby
 
require 'cgi'
cgi = CGI.new
cgi['name']    # => "Zara"
cgi.params['name'] # => ["Zara", "Huma", "Nuha"]
cgi.keys      # => ["name"]
cgi.params     # => {"name"=>["Zara", "Huma", "Nuha"]}
Copy after login

注意:Ruby 会自动判断 GET 和 POST 方法,所以无需对两种方法区别对待。

以下是相关的HML代码:

<html>
<body>
<form method="POST" action="http://www.example.com/test.cgi">
First Name :<input type="text" name="FirstName" value="" />
<br />
Last Name :<input type="text" name="LastName" value="" />
 
<input type="submit" value="Submit Data" />
</form>
</body>
</html>
Copy after login

创建 Form 表单和 HTML

CGI 包含了大量的方法来创建 HTML,每个HTML标签都有相对应的方法。 在使用这些方法前,比必须通过 CGI.new 来创建 CGI 对象。

为了使标签的嵌套更加的简单,这些方法将内容作为了代码块,代码块将返回字符串作为标签的内容。如下所示:

#!/usr/bin/ruby
 
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
     }
   }
  }
}
Copy after login

字符串转义

当你在处理 URL 中的参数或者 HTML 表单数据时,需要对指定的特殊字符进行转义,如:引号("),反斜杠(/)。

Ruby CGI 对象提供了CGI.escape 和 CGI.unescape 方法来处理这些特殊字符的转义:

#!/usr/bin/ruby
 
require 'cgi'
puts CGI.escape(Zara Ali/A Sweet & Sour Girl")
Copy after login
Copy after login

以上代码执行结果如下:

#!/usr/bin/ruby
 
require 'cgi'
puts CGI.escape(Zara Ali/A Sweet & Sour Girl")
Copy after login
Copy after login

另一组实例:

#!/usr/bin/ruby
 
require 'cgi'
puts CGI.escapeHTML('<h1 id="Zara-Ali-A-Sweet-Sour-Girl">Zara Ali/A Sweet & Sour Girl</h1>')
Copy after login

以上代码执行结果如下:

<h1 id="Zara-Ali-A-Sweet-Sour-Girl">Zara Ali/A Sweet & Sour Girl</h1>'
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth analysis of the similarities and differences between Golang and Ruby In-depth analysis of the similarities and differences between Golang and Ruby Jun 01, 2024 pm 08:46 PM

The main difference between Go and Ruby is that Go is a statically typed compiled language that supports lightweight parallelism and efficient memory management, and is suitable for writing high-concurrency applications; Ruby is a dynamically typed interpreted language that supports true parallelism but memory management It requires manual control and is suitable for writing flexible web applications.

Why have Python, Ruby and other languages ​​deprecated the increment operator? Why have Python, Ruby and other languages ​​deprecated the increment operator? May 11, 2023 pm 04:37 PM

Many people may notice a phenomenon, that is, in some modern programming languages ​​​​(of course, not referring to "recent" programming languages), the increment and decrement operators have been cancelled. In other words, there is no such expression as i++ or j-- in these languages, but only i+=1 or j-=1 Such an expression. This answer will explore the background and reasons for this phenomenon from the perspective of design philosophy. Strictly speaking, it may be biased to say "i++ is disappearing", because it seems that only Python, Rust and Swift among mainstream programming languages ​​do not support the increment and decrement operators. When I first came into contact with Python, this was also

How does Ruby use Mysql2 connection to operate MySQL? How does Ruby use Mysql2 connection to operate MySQL? Apr 17, 2023 pm 10:07 PM

Ruby operates MySQL using mysql2 to connect to mysql and operate mysql. geminstallmysql2 connects to mysql to establish a connection: require'mysql2'conn=Mysql2::Client.new({host:'192.168.200.73',username:'root',password:'P@ssword1!'}) The accepted connection options include: Mysql2::Clie

How to implement a simple data conversion function using MySQL and Ruby How to implement a simple data conversion function using MySQL and Ruby Sep 21, 2023 am 08:07 AM

How to use MySQL and Ruby to implement a simple data conversion function. In actual development work, data conversion is often required to convert one data format into another data format. This article will introduce how to use MySQL and Ruby to implement a simple data conversion function, and provide specific code examples. First, we need to install and configure the MySQL and Ruby environments. Make sure you have a MySQL database installed and can connect to the database via the command line or other tools. In addition, you need to install

How to use MySQL and Ruby to implement a simple data analysis report function How to use MySQL and Ruby to implement a simple data analysis report function Sep 20, 2023 pm 05:09 PM

How to use MySQL and Ruby to implement a simple data analysis report function Introduction: In today's data-driven era, data analysis plays a crucial role in corporate decision-making and development. As an important part of data analysis, data analysis reports are of great significance for organizing, visualizing and interpreting data. This article will introduce how to use MySQL and Ruby to implement a simple data analysis report function, and provide corresponding code examples. 1. Database design and table creation must realize data analysis and reporting functions

How to implement a simple asynchronous task scheduling function using MySQL and Ruby How to implement a simple asynchronous task scheduling function using MySQL and Ruby Sep 20, 2023 am 10:48 AM

How to use MySQL and Ruby to implement a simple asynchronous task scheduling function. Most of the previous web applications used a synchronous method to process requests, that is, after the user sends a request, the server will immediately process the request and return the result. However, as the complexity of applications increases, the processing efficiency of synchronous methods gradually becomes inefficient, so asynchronous task scheduling has become a common requirement in modern web applications. This article will introduce how to use MySQL and Ruby to implement a simple asynchronous task scheduling function, including task

How to build scalable web applications using Vue.js and Ruby How to build scalable web applications using Vue.js and Ruby Aug 03, 2023 pm 02:27 PM

How to use Vue.js and Ruby language to build scalable web applications. In recent years, with the development and growing needs of web applications, building scalable web applications has become an important topic. As a lightweight JavaScript front-end framework, Vue.js provides a flexible, efficient and scalable solution. At the same time, Ruby, as a concise and easy-to-read programming language, can be used to construct powerful back-end systems. This article will introduce how to combine Vue.js and Ruby language to build

Dive deeper: Website building alternatives to PHP Dive deeper: Website building alternatives to PHP Mar 21, 2024 am 08:51 AM

In today's Internet age, website building has become one of the indispensable skills for many people. As a widely used back-end programming language, PHP is known and used by many developers. However, there are many other options for building a website besides PHP. This article will give you an in-depth look at your website building options other than PHP and provide you with concrete code examples. PythonPython is a powerful and easy-to-learn programming language that is widely used in web development. Using Python

See all articles