14. 第二阶段 基于图形的 HTML 文档
1993 年出现了第一个支持图形的浏览器 NCSA Mosic Mosic 是一群大学生和 Netscape
的奠基人 MarcAndreesen 共同为国际超级计算机应用中心 National Center of Superco-
mputing Applications NCSA 开发的 Web 浏览器 此时 Web 的概念已经在各个科研机
构中得到广泛应用 图形浏览器的出现 为 Internet 开辟了新的广阔天地 使得 Web 的
访问更加容易 更加具有趣味性 在同一时期图形环境很快超过基于字符的桌面系统并流
行起来
图形桌面系统加上图形 Web 浏览器 这正是人们期盼以久的梦幻组合 在仅仅几个
月的时间内 在计算机界掀起一种狂热的竞争 计算机公司 机构开始为 Web 提供内容
或是为客户提供 Web 服务
这时的 Web 仍然是静态的 Web 的内容包括文本 图形 有些还包括一些声音或视
频文件 不过这时的声音或视频文件需要单独下载 然后使用外部应用程序来进行播放
第三阶段 Dynamic HTML 文档
在 Web 发展的第一和第二阶段中 Web 页是使用 HTML 文本编辑器来编写 然后放
在 Web 服务器中供人们访问 放置于 Web 服务器上的 Web 页在大多数情况下都是不会
改变的 除非 Web 作者进行修改 这些保持不变的 Web 页一般能满足大多数用户的要求
而对一些特别的用户来说这还是不够的 比如一个为用户提供产品目录信息的 Web 站点
每个用户需要查看的内容可能会各不相同 如果使用长期保持不变的 Web 页显然不能满
足用户要求
为了实现动态产生 Web 页 Web 页作者开始使用公用网关接口 CGI 来编写服务
器端的 Web 页应用程序 CGI 程序使得用户和浏览器可以进行低级的交互行为
第四阶段 Active HTML 文档
从 1995 年开始 人们开始在 Netscape Navigator 中使用插件和 Java 这一阶段最大的
特点就是客户端 浏览器的功能得到加强 不再单独依靠服务器来运行应用程序和处理
用户信息 JavaScript Java ActiveX 和其它客户端扩展功能的应用 使得客户端对服务
器的依赖性减小 使浏览器和服务器成为真正的客户/服务器结构 浏览器成为一个功能
强大的可以运行 Web 应用程序的操作环境
1.4 Web 应用程序结构
以 Web 作为应用程序开发环境正逐渐成为一种趋势 随着 Java JavaScript ActiveX
和其它技术的出现 越来越多的人将兴趣集中到开发 Web 应用程序上 使用 Web 作为应
用程序开发环境听起来有点让人感到迷惑 因为 Web 具有分布性的特点 所以 Web 应用
程序的构成是多方面的 需要多种技术的支持
在基于局域网的客户/服务器机构中 非常典型的应用可能就是基于客户端的数据库
网络应用程序 也许你曾经使用过一些单独的工具开发过客户端应用程序 如使用 Visual
Basic 或 Delphi 而在服务器端的典型开发和维护工具恐怕要数 SQL Server
图 1-2 显示了 Web 应用程序的各个组成部分 Web 应用程序结构可以看成是各种 Web
15. 技术的集成 开发 Web 应用程序使用的每一种技术都具有一定的局限性 应用范围相当
狭小 但它们在一起使用 则可以提供有效的方法来解决 Internet 或 Intranet 应用程序的
开发问题
图1-2 Web 应用程序结构
1.4.1 客户端 Web 应用程序
客户端 Web 应用程序可以划分成以下四个部分
浏览器
HTML Hypertext Markup Language 超文本标记语言
客户端扩展 Java Applets ActiveX 和 Netscape 插件
脚本编写语言 JavaScript JScript 和 VBScript
图 1-3 显示了客户端的各种 Web 技术是如何一起工作的 下面我们将分别介绍客户
端的各种技术
1. 浏 览 器
浏览器毫无疑问是 Web 应用程序中最重要的组成部分 用户访问 Web 页 Web 应用
程序的运行 都必须在浏览器中进行 浏览器的技术相对简单一些 只需要能够正确地从
Web 服务器下载 Web 页 并将其显示在浏览中 浏览器并没有一个同一的标准 当前最
常用的浏览器是 Netscape Navigator 和 Microsoft Internet Explorer 不同的浏览器对各种
Web 技术有不同程度的支持 所以在不同的环境中选择浏览器对开发 Web 应用程序起着
关键作用
如果开发的是 Intranet 内网 的 Web 应用程序 那你可以确定客户端的用户使用一
个标准的浏览 如使用 Netscape Navigator 或 Microsoft Internet Explorer 在确定了浏览器
的前提下 Web 应用程序的开发将相对简单 而当我们将开发的 Web 应用程序发布到
Internet 上 由于客户端用户使用的浏览器是多种多样 Web 应用程序的开发将变得复杂
16. 起来 表 1-1 列出了各种浏览器对各种 Web 技术的支持情况
图1-3 客户端 Web 技术
表1-1
Netscape Navigator Microsoft Internet Explorer
JavaScript 2.0+ 3.0+
VBScript 不支持 3.0+
Java 2.0+ 3.0+
ActiveX 控件 3.0+插件 3.0+
Netscape 插件 2.0+ 3.0+
2 HTML
HTML 也是进行 Web 应用程序开发的主要技术之一 HTML 是一种标记语言 严格
地讲 HTML 并不能称之为语言 HTML 是使用各种预先定义的标记对文本进行标注 被
标注的文本相当于进行了格式化 HTML 的特点就是简单 正是这种简单的特性使它更
易于使用
被标注的 HTML 文档最终在浏览器中显示出实际的效果 如果仅使用 HTML 我们
可以创建静态的 Web 文档 如返回服务器端的查询结果 使用反馈表单或者显示 JavaScript
应用程序结果等 Web 应用程序的开发是离不开 HTML 的 比如 JavaScript 应用程序便
需要使用 HTML 标签嵌入到 HTML 文档中才能起作用
3 客户端扩展
客户端扩展功能是扩展浏览器的功能 随着活动 Web 页功能的不断地加强 仅仅靠
加强浏览器的功能还是不够的 所以需要对浏览器的功能进行扩展 客户端的扩展都是在
浏览器中使用第三方的附加软件来加强浏览器的功能 第三方附加软件需要和浏览器一起
工作 但并没有和浏览器绑定到一起
现在出现的第三方客户端扩展功能在功能上具有相似之处 但仍然有各自的特点 主
18. 1.4.2 服务器端 Web 技术
服务器端 Web 应用程序结构主要由 Web 服务器和服务器软件扩展组成 服务器的扩
展技术很多 图 1-4 显示了服务器端 Web 应用程序结构中各种 Web 技术的关系
图1-4 服务器端 Web 应用程序结构
1 Web 服务器
Web 服务器实际上是基于 TCP/IP 的应用程序 它的主要作用就是处理客户端的 HTML
文档中的表单发出的请求 然后将结果返回给客户端的浏览器供用户查看 现在主要的几
种 Web 服务器有 Netscape Enterprise Server NES Microsoft Internet Information Server
IIS 和 Apche
2 服务器扩展
从 Web 服务器自身的角度讲 它只能在浏览器进行请求的情况下向浏览器提供静态
的 HTML 文档 为了产生动态的 Web 页 需要对 Web 服务器的功能进行扩展 这些扩
展技术包括 CGI 服务器 API JavaScript 和 Java
CGI
CGI 是公用网关接口 Common Gateway Interface 的简称 是在 Web 服务器中使用
外部程序的接口方法 我们可以在服务器上运行 CGI 程序或者脚本来产生动态的 Web 内
容供客户端用户查看 通常情况下 CGI 程序用于在服务器端处理客户端浏览器中的 HTML
文档中的表单请求 CGI 程序或者脚本被放在 Web 服务器中一个特殊的目录之中 它们
接收到客户端的请求 进行处理 然后将结果以 HTML 文档的方式返回到客户端
CGI 程序的典型应用是用来处理用户发出的数据库查询请求 将查询结果以 Web 页
的方式返回给客户端的用户
在服务器端可用于编写 CGI 程序的程序设计语言很多 只要是能在服务器端运行的
程序设计语言 不一定要 Web 服务器的支持 都可以用来编写 CGI 程序 如 Java
C C ++ Visual Basic 或 PHP 在 Unix 操作系统中经常使用 Perl 来编写 CGI 程序
服务器 API
服务器 API 是 Web 服务器为编程人员提供的应用程序编程接口 API Application
19. Programs Interface 两种最常用的服务器 API 是 Netscape Server API NSAPI 和 Microsoft
Internet Server API ISAPI API 与服务器是紧密集成的 如在 Windows 环境中可以使
用 API 来创建由服务器访问的 DLL 动态链接库 而不是单独的 EXE 文件
使用服务器 API 的优点是它具有比 CGI 程序更好的性能 因为在使用 CGI 的情况下
当遇到客户端的请求时 每一个请求都会单独运行一遍 CGI 程序 造成资源的浪费 同
时也会使数据共享的性能下降
使用服务器 API 的一个不足的地方是 服务器的 API 是针对某个特定服务器的 不
同的服务器具有不同的 API 不同的服务器 API 是很难相互兼容的 比如 使用 ISAPI IIS
服务器的 编写的 DDL 就不能在 Netscape 服务器中使用 这就限制了使用服务器 API 程
序只能在相同的服务器上使用 当然 如果在使用一种服务器的情况下 用不着考虑这种
情况了
服务器端的 JavaScript
很多人都知道 JavaScript 可以用来编写客户端的脚本程序 其实 JavaScript 同样可以
用在服务器中 在服务器端对 JavaScript 提供支持只有 Netscape 服务器 Netscape 服务器
端的 JavaScript 称为 SSJS 可以用来编写由 Netscape 服务器控制的应用程序 JavaScript
在服务器端产生动态 HTML 文档的功能得到了扩展 包括 与客户端通信 在服务器端
访问外部文件和连接 SQL 数据库
Microsoft 也允许用户在 ASP Active Server Pages 中使用 Jscript 编写的脚本程序
Java
最近 Java 在服务器端的应用得到了巨大发展 Sun 公司发布了新的 Java 技术 JavaServer
Pages JSP 从其名称可以看出 JSP 是与 ASP 和 SSJS 进行竞争的技术 现在 Sun 与
Netscape 已结成同盟 称为 iPlanet 准备将 JSP 和 SSJS 融合到一起 构成一个新的 具
有超强功能的技术
另外有一些读者也许听说过 Java Servlet Servlet 是一种小的组件 有点像在 ASP 中
使用的 ActiveX 控件 Servlet 可以在 HTML 文档中被调用或者是用于创建 HTML 文档
Servlet 是为了让用户使用 Java 语言来建立快速 可靠 与平台无关的组件以便创建 Web
应用程序
1.5 JavaScript 与 VBScript
正如我们在前面提到的一样 JavaScript 并不是惟一可用的 Web 脚本语言 VBScript
和 JavaScript/JScript 一样可以用于编写 Web 脚本应用程序 VBScript JavaScript 和 JScript
虽然都是处于竞争的地位 但实际上它们之间又有互相补充的作用 在本节我们将 对
VBScript 和 JavaScript 进行比较 这将有助于我们学习 JavaScript
1.5.1 关 于 VBScript
VBScript 是 Microsoft 开发的和 JavaScript 进行竞争的一种 Web 脚本语言 从语言发
28. 第2章
JavaScript 与 HTML
主要内容
HTML 基 础
将 JavaScript 脚本嵌入 HTML 文档
编写自己的 JavaScript 脚本
本 HTML 在众多的 Web 技术中恐怕是最显得微不足道的了 但
章 HTML 的的确确是精彩的 Web 世界必不可少的基石 使用 HTML 可
导 以创建静态的 内容丰富的 有趣的 Web 页 这在 Internet 世界的
读 初期可说是一个创举 使用 JavaScript 可以为 HTML 文档增加交互
性 增强对用户操作的反应能力 使 Web 页更加具有吸引力
29. 换一个角度 可以将 JavaScript 看做是 CGI 程序的一个发展的新阶段 CGI 是基于服
务器端的应用程序 而 JavaScript 则是基于客户端的 通过使用 JavaScript Web 开发人
员可以编写脚本 然后将脚本嵌入到 HTML 文档中来创建动态的 Web 页 JavaScript 将
原来需要使用 CGI 程序在服务器端完成的处理操作放在客户端来完成 这样大大减少对
用户操作的响应时间 使用户可以在更短的时间内完成更多的事
我们知道 JavaScript 是嵌入到 HTML 文档中的 JavaScript 代码的运行在很多时候也
需要通过 HTML 对象的事件进行驱动 所以无论对于 Web 开发人员还是阅读 HTML 文档
了解 HTML 的基本知识还是很重要的
2.6 HTML 基 础
开发简单的 HTML 文档 标签和表单是件非常容易的事 在 HTML 中的大多数标签
都有一些复杂的属性 使用复杂的标签和属性可以创建更复杂 可用性更强的 Web 页
HTML 标准始终在不断地变化 当前的 HTML 版本为 4.01 HTML 的一个新的版本
名称将是 XHTML 不过这还需要得到 Word Wide Web W3C 的同意 Web 开发人员
可以随时从 W3C 的 Web 站点 http://www.w3.org 中查看有关 HTML 的各种信息 如图 2-1
所示
图2-6 W3C 上的 HTML 信息
HTML 的标准和浏览器都是在不断发展 当我们在使用 HTML 标签 特别是一些新
的标签时 必须要确保浏览器能够支持它 另外 在不同的浏览器中 也会出现一些非标
准的标签 如<marquee>标签只能在 Internet Explorer 中使用 Navigator 是不支持的 而
Navigator 中的<layer>和<ilayer>同样也不能在 Internet Explorer 中使用
所以 当我们在编写 HTML 文档时 应充分考虑多浏览器的因素 能让多种不同浏
览器都能阅读是衡量 HTML 文档好坏的一个标准
30. 2.6.2 HTML 基本知识
在客户端的 JavaScript 脚本和 HTML 文档的关系是非常密切的 所以在我们编写脚本
之前 必须先熟悉 HTML 文档的结构和 HTML 标签 当对 HTML 掌握后 编写 Web 页
将是非常简单的事 通常 一个 Web 页是由文本 标签和一些注释组成的
Web 页中的文本是最简单 最容易理解的 输入到 Web 页中的文本是我们需要向用
户展示的内容 标签则是 Web 页中最重要 需要花时间学习的东西 一个 HTML 标签通
常是由 < 开头 由 > 结尾的标志 标签的作用就是告诉浏览器该如何显示我们书
写的文本
HTML 标签有单独标签和成对标签 单独标签如<hr>和<br> 它们都是单独使用的
<hr>的作用是显示一条水平直线 <br>是用于进行换行 单独标签通常又称之为空标签
空标签只能单独使用 不能用于格式化文本
成对标签又称之为容器 它使用一个开始标签和一个结束标签来标识文本 结束标签
是在一个标签的名称前加一个 / 如下面使用的 <title> 标签
<title>学习 JavaScript</title>
在<title>和</title>之间的是容器标识的文本 学习 JavaScript 被标记为一个 HTML
文档的标题
一些 复杂 的标 签还 可以通过 设置 属性 来控 制标 签的 显示效果 如 <hr width=200
color=red>定义了一条长 200 个像素 颜色为红色的水平线 很多 HTML 标签都具有自己
的属性
还有一些特殊的标签 它们必须放在其它的容器之中才能够使用 比如<input>必须
放在<form>标签内 <li>必须放在<ol>标签内 所有的其它 HTML 标签都放在<html>和
</html>之间
在 HTML 文档中 如果需要 有时会加入适当的注释对文档进行说明 注释的内容
不会显示在浏览器中 在 HTML 文档中加入注释使用 <!--注释--> 例如
<!--使用 JavaScript 方法-->
2.6.3 HTML 文档结构
HTML 文档的结构是非常重要的 标签在文档中放置的位置的不同 会有不同的显示
效果 最简单的 HTML 文档结构如下
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
在<HTML>和</HTML>之间放置了 HTML 文档的所有内容 在<BODY>和</BODY>
31. 之间放置的是实际要显示的文本内容和其它用于控制文本显示方式的标签
下面是一个简单的 HTML 文档
<html>
<head>
<title>一个简单的 HTML 文档</title>
<script type="text/JavaScript"></script>
</head>
<body>
<h1>简单的 HTML 文档</h1>
<ol type=1>
<li>Java</li>
<li>JavaScript</li>
<li>Visual Basic</li>
<li>VBScript</li>
</ol>
<table width="3" height="3" border>
<tr>
<th colspan="12">表格</th>
</tr>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
</tr>
<tr>
<td>Four</td>
<td>Five</td>
<td>Six</td>
</tr>
</table>
<p>
<form>
<input name="button1" type="submit">
</form>
</p>
这是一个简单的 HTML 文件
</body>
</html>
该 HTML 文档在 Microsoft Internet Explorer 中的实际效果如图 2-2 所示
32. 图2-7 一个简单的 HTML 文档
2.6.4 公 共 属 性
在前面我们已经提到 HTML 的许多标签都具有属性 属性用于控制标签怎样操作和
如何显示 并不是所有的标签都具有属性 有一些标签具有公共的属性 这些属性的名称
和作用都完全相同 在表 2-1 中列出了 HTML 标签的共同属性和作用
表2-3
属性 作用
class 指明 HTML 标签所属的类 class
id 定义一个惟一的标识 在整个文档中标识该标签
name 为标签命名 该名称可以在 JavaScript 或 CGI 脚本中引用
style 指明标签使用的样式 style
2.7 在 HTML 文档中嵌入 JavaScript
JavaScript 代码使用<script>和</script>集成到 HTML 文档中 在一个 HTML 文档中
可以有多对<script>和</script>来嵌入多段 JavaScript 代码 每个 JavaScript 代码中可以包
含一条或多条 JavaScript 语句
<script>也有几个属性 它们的作用如表 2-2 所示
33. 表2-4
属性 作用
defer 属性值为 boolean 值 用于告诉浏览器脚本是否有输出内容
language 用于指定脚本使用的语言 现在已经很少使用该属性
src 指定使用的外部 JavaScript 代码的 URL 地址
type 代替 language 属性 用于指明脚本使用的语言
Defer
Defer 是一个简单的属性 它的作用就是告诉浏览器 JavaScript 代码是否会产生输出
也可以说 document.write()方法是否被使用 下面是一个简单的例子
<script type="text/JavaScript" defer>
<!--
//仅仅声明了一个变量 没有输出语句
var myInt=2000
//-->
</script>
language
language 属性在最近的 HTML 和 XHTML 中已经不再使用 但为了使以前的 Web 也
仍能够不加修改就可以在浏览器中正确地显示 所以现在的<script>仍保留了 language 属
性
language 属性的使用格式如下
<script language ="JavaScript">
该标签告诉浏览器脚本使用的是 JavaScript 1.0 如果是使用其它版本的 JavaScript
如 1.1 可以按照如下格式使用
<script language ="JavaScript 1.1">
language 属性的值告诉浏览器应该按照哪一种语言的版本来执行脚本代码 在表 2-3
中列出了 language 属性值可用的 JavaScript 版本和支持的浏览器
表2-5
language 属性值 支持的浏览器
JavaScript Navigator 2+和 Internet Explorer 3+
JavaScript 1.1 Navigator 3+和 Internet Explorer 3+
JavaScript 1.2 Navigator 4+和 Internet Explorer 4+
JavaScript 1.3 Navigator 4.05+和 Internet Explorer 5+
JavaScript 1.4 HotJava 3+和早期 alpha 版本的 Mozilla/Navigator 5 pre_M12
JavaScript 1.5 Mozilla/Navigator beta 1.0 M12+
如果在<script>中没有使用 language 属性 则浏览器会假设使用的是 JavaScript 1.0
我们可以利用 language 属性 在 Web 页中编写多种版本的程序代码 这样浏览器可以通
过判别语言的版本来执行它支持的代码 同时会忽略它不支持的代码
下面的 HTML 文档可以用于测试浏览器支持的 JavaScript 版本
<html>
<head>
<title>JavaScript 版本测试</title>
112. </BODY>
<SCRIPT LANGUAGE = JavaScript>
function DisplayMessage(form1)
{
form1.Textarea.value = "Hello from JavaScript"
}
</SCRIPT>
</HTML>
下面的代码是用来清除文本区域对象中的文本 并且赋予另外一文本信息
<SCRIPT LANGUAGE = JavaScript>
function DisplayMessage(form1)
{
form1.Textarea.value = "Hello from JavaScript"
}
</SCRIPT>
实例在浏览器中预览效果如图 6-3 所示
图6-38
113. 第7章
按 钮 对 象
主要内容
按 钮 对 象
复选框对象
Radio 对 象
本 本章主要通过具体的实例来介绍在 Web 页面中常用的三种按
章 钮对象 普通按钮 提交按钮 复位按钮对象 以及复选框对象和
导 Radio 对象在 Web 页面中的运用
读
114. 7.21 button submit reset 对 象
在 HTML 表单中定义了三种类型的按钮 按钮 button 提交 submit 和复位 reset
对象 使用 HTML 语法定义按钮如下
<INPUT
TYPE=”button|submit|reset”
NAME=”objectname”
VALUE=”labeltext”
OnClick=”methodName”>
三种类型的按钮看起来非常相似 但是它们的使用目的却不一样 它们的使用目的定
义如下
提交 submit 按钮 提交按钮对象是用来提交数据信息给服务器的处理程序
JavaScript 代码不干涉该按钮的活动 且这些都是按钮本身属性完成的
复位 reset 按钮 复位按钮对象是用来清除表单对象中各个文本域的文本信息
并且将各个缺省的值赋予文本对象域 同理 JavaScript 代码也是不干涉该按钮
的活动 且这些都是按钮本身属性完成的
按钮 button 这是一个普通的按钮对象 为了使用该按钮完成某项工作 需
要增加一个 onClick 处理事件来驱动该按钮
在下面的实例中我们将使用三种类型按钮 使用提交按钮来提交信息 使用复位按钮
来清除表单中的文本域中信息 使用按钮来显示一个帮助用户填充注册信息的窗口 下面
是实例程序的代码清单
<html>
<head>
<title>Online Registration</title>
<SCRIPT LANGUAGE="JavaScript">
function showHelp() {
helpWin = window.open("", "Help", "height=200,width=400")
helpWin.document.write("<body><h2>Help on Registration</h2>")
helpWin.document.write("1. Please enter your product information into the fields.<p>")
helpWin.document.write("2. Press the Register button to submit your form.<p>")
helpWin.document.write("3. Press the Clear button to clear the form and start again.<p>")
helpWin.document.write("<p>")
helpWin.document.write("<form><DIV ALIGN='CENTER'>")
helpWin.document.write("<input type=button value=' OK 'onClick ='window.close()'>")
helpWin.document.write("</DIV></form></body>")
}
</SCRIPT>
115. </head>
<body>
<h1>Online Registration</h1>
<form method="POST">
<p>Please provide the following product information:</p>
<blockquote>
<pre><em> Product name </em><input type=text size=25 maxlength=256
name="ProductName">
<em> Model </em><input type=text size=25 maxlength=256
name="Product_Model">
<em> Version number </em><input type=text size=25 maxlength=256
name="Product_VersionNumber">
<em>Operating system </em><input type=text size=25 maxlength=256
name="Product_OperatingSystem">
<em> Serial number </em><input type=text size=25 maxlength=256
name="Product_SerialNumber">
</pre>
</blockquote>
<p><input type=submit value="Register"> <input type=reset value="Clear">
<input type=button value="Help" onClick="showHelp()"></p>
</form>
</body>
下面的代码是在用户单击帮助按钮后产生的 Web 页面
<SCRIPT LANGUAGE="JavaScript">
function showHelp() {
helpWin = window.open("", "Help", "height=200,width=400")
helpWin.document.write("<body><h2>Help on Registration</h2>")
helpWin.document.write("1. Please enter your product information into the fields.<br>")
helpWin.document.write("2. Press the Register button to submit your form.<br>")
helpWin.document.write("3. Press the Clear button to clear the form and start
again.<br>")
helpWin.document.write("<p>")
helpWin.document.write("<form><DIV ALIGN='CENTER'>")
helpWin.document.write("<input type=button value=' OK 'onClick='window.close()'>")
helpWin.document.write("</DIV></form></body>")
}
</SCRIPT>
实例程序在浏览器中预览的效果如图 7-1 所示
134. 第10章 象
history
对
主要内容
history 对象的属性 方法
本 本章主要通过两个具体的实例来介绍历史对象的 current
章 length next previous 属性以及 Back Forward Go 方
导 法的运用
读
135. 当我们在 Internet 上进行网上冲浪时 浏览器会自动维护一个用户最近访问的 URL
列表 这个列表是由 history 对象在 JavaScript 中完成的 一般来说在该列表中的 URL 是
不能通过 Script 秘密获取的
对于 history 对象及其它内部的 back 或 go 方法运用 HTML 文档中提供的 Back
按钮的替代功能 这个按钮触发了一个 Script 检查历史记录表中的所有元素 然后返回
一个网页 您的文档不必知道任何关于用户是从哪里登录到您的 Web 页面的 URL 中的
History 对象的主要属性如下 current length next previous 等 主要方法如下 Back
Forward Go 等
我们这里主要介绍 history 对象的 length 属性 用 history 对象的 length 属性来计算历
史记录列表中的元素 但是这个有价值的信息在编写与当前位置相关的导航脚本中并不是
十分有用 因为在脚本中不能从历史记录队列中当前文档所在处得到任何东西 但是如果
当前文档在列表的顶端 那么我们可以计算文档的相对位置
在下面的实例中我们将使用简单的函数来显示基于浏览器的历史记录中元素的个数和
两个警告信息之一 下面是实例程序的代码清单
<HTML>
<HEAD>
<TITLE>
HISTORY 对象
</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
function showCount()
{
var hisCount=window.history.length
if (hisCount>5)
{
alert(“you have been busy, you have visited”+hisCount +”page so far”)
}
else
{
alert(“you have been to ”+gusCount +”Web pages this session.”)
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT TYPE=”button” NAME=”activity” VALUE=”激活” onClick=”showCount()”>
</FORM>
</BODY>
</HTML>
在下面的实例中我们将利用 history 对象的常用属性 方法来创建一个 Web 页面 下
面是实例的代码清单
<html>
136. <head>
<title>History 对象</title>
</head>
<body bgcolor="#FFFFFF">
<SCRIPT LANGUAGE="JavaScript">
<!--
function goPrev()
parent.frames[1].history.back()
}
function goNext()
parent.frames[1].history.forward()
}
function moveOn()
var urlAddress = ""
urlAddress = document.forms[0].LocationBox.value
if (urlAddress != "")
parent.frames[1].location = urlAddress
document.forms[0].ListLen.value = parent.frames[1].history.length }
else
alert("请在单击按钮之前输入文本信息.")
}
}
function jump()
if (document.forms[0].goParam[1].checked)
var goVal = 0
goVal = parseInt(document.forms[0].GoBox.value) }
else
var goVal = ""
goVal = document.forms[0].GoBox.value
}
parent.frames[1].history.go(goVal)
}
function getParentInfo()
myParentTitle = parent.document.title
alert(myParentTitle)
}
// -->
</SCRIPT>
<form method="POST">
<h3><em>Ways to navigate</em></h3>
<ul>
<li>使用 location 对象.</li>
</ul>
<p><input
type=text
size=20
maxlength=50
211. -->
</style>
</head>
<body>
<p>
Here is some text that has global styles applied, but
<span id="smaller">here is some smaller text</span> in
the middle of this paragraph.
</p>
</body>
</html>
在该页面中 设置的 ids 属性
格式如下
#smaller{
font-size: 12pt;
}
在该格式中 设置字体的显示
的大小为 12 点大小
在 ids 属 性 的 设 置 中 以
#smalle{ 来设置格式的标头
然后在文档的使用中 为设置的 ids 图16-3
属性指定一个 id 标识
<span id="smaller">
该页面控制的显示效果如图 16-3 所示
16.3.2 设置类 class 属性
class 控制文档元素类别显示格式 在应用中的格式与 ids 属性相同 在设置的过程中
是以 . 开头来设置的 请看下边的实例
<html>
<head>
<style type="text/css">
<!--
h1{
color: green;
}
#ital{
font-style: italic;
}
.newheader{
color: yellow;
}
#myid{
font-size: 12pt;
212. }
-->
</style>
</head>
<body>
<h1>Green</h1>
<h1 class="newheader" id="myid">Yellow and point size 12</h1>
<h1 class="newheader">Yellow and <span id="ital">italic</span></h1>
<h2>This will be default text<h2>
</body>
</html>
在该格式的定义中 设置了一个名为 newheader 的类属性 控制文本字体的显示
色彩
.newheader{
color: yellow;
}
在类的使用中 一般在文档元素中以关键字 class 指明类的应用 利用 class 关键字来
规定文档应用到设置中的格式
<h1 class="newheader">
该页面的显示情况如图 16-4 所示
图16-4
16.3.3 tag 属 性
该属性用来设置文档 html 标记的样式单属性 一般用来指定一级标题的显示 文档
主体的字体格式 段落的显示外观等等
该格式在应用时 只要定义了 html 标记的属性 在文档中就自动使用设置的格式
无需用户再来设置 请看下边的实例
<html>
<head>
<style type="text/css">
<!--
213. p{
font-style: italic;
font-size: 24pt;
}
#smaller{
font-size: 12pt;
}
-->
</style>
</head>
<body>
<p>
Here is some text that has global styles applied, but
<span id="smaller">here is some smaller text</span> in
the middle of this paragraph.
</p>
</body>
</html>
该格式定义对段落 p 的显示外观的控制 并设置了段落字体显示为斜体 大小为 24
点 在文档显示时将自动执行设置的格式 在浏览器中显示的情况如图 16-5 所示
图16-5
220. if (!document.layers&&!document.all)
event="test"
function showtip2(current,e,text){
if (document.all&&document.readyState=="complete"){
document.all.tooltip2.innerHTML='<marquee style="border:1px solid black">'+text+'</marquee>'
document.all.tooltip2.style.pixelLeft=event.clientX+document.body.scrollLeft+10
document.all.tooltip2.style.pixelTop=event.clientY+document.body.scrollTop+10
document.all.tooltip2.style.visibility="visible"
}
else if (document.layers){
document.tooltip2.document.nstip.document.write('<b>'+text+'</b>')
document.tooltip2.document.nstip.document.close()
document.tooltip2.document.nstip.left=0
currentscroll=setInterval("scrolltip()",100)
document.tooltip2.left=e.pageX+10
document.tooltip2.top=e.pageY+10
document.tooltip2.visibility="show"
}
}
function hidetip2(){
if (document.all)
document.all.tooltip2.style.visibility="hidden"
else if (document.layers){
clearInterval(currentscroll)
document.tooltip2.visibility="hidden"
}
}
function scrolltip(){
if (document.tooltip2.document.nstip.left>=-document.tooltip2.document.nstip.document.width)
document.tooltip2.document.nstip.left-=5
else
document.tooltip2.document.nstip.left=150
}
</script>
<script LANGUAGE="JavaScript">
function YY_Layerfx(yyleft,yytop,yyfnx,yyfny,yydiv,yybilder,yyloop,yyto,yycnt,yystep) { //v1.2
//copyright (c)1999 Yaromat, Jaro von Flocken
if ((document.layers)||(document.all)){
with (Math) {yynextx= eval(yyfnx)}
with (Math) {yynexty= eval(yyfny)}
yycnt=(yyloop && yycnt>=yystep*yybilder)?0:yycnt+yystep;
if (document.layers){
eval(yydiv+".top="+(yynexty+yytop))
eval(yydiv+".left="+(yynextx+yyleft))
}
274. cookie 文件 检索 cookie 以及显示用户设置和选择的 cookie 文件
该示例的特性如下
Cookie 信息存放的方法
Cookie 文件的设置方法
Cookie 文件的存储
Cookie 文件的检索
Cookie 文件的清除
利用 JavaScript 动态生成页面
利用 JavaScript 数组设置数据表
20.59 程序源代码
实现如上特性的源代码如下
<html>
<head><script language="JavaScript">
<!--
//显示存在的 cookie.
function GetCookie(name)
{
var result = null;
var myCookie = " " + document.cookie + ";";
var searchName = " " + name + "=";
var startOfCookie = myCookie.indexOf(searchName);
var endOfCookie;
if (startOfCookie != -1)
{
startOfCookie += searchName.length;
// skip past cookie name
endOfCookie = myCookie.indexOf(";", startOfCookie);
result = unescape(myCookie.substring(startOfCookie,endOfCookie));
}
return result;
}
//设置 cookie.
function SetCookieEZ(name, value)
{
document.cookie = name + "=" + escape(value);
}
275. function SetCookie(name, value, expires, path, domain, secure)
{
var expString = ((expires == null)? "" : ("; expires=" + expires.toGMTString()));
var pathString = ((path == null) ? "" : ("; path=" + path));
var domainString = ((domain == null)? "" : ("; domain=" + domain));
var secureString = ((secure == true) ? "; secure" : "");
document.cookie = name + "=" + escape(value)+ expString + pathString + domainString+
secureString;
}
//清除 cookie.
function ClearCookie(name)
{
var ThreeDays = 3 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime (expDate.getTime() - ThreeDays);
document.cookie = name + "=ImOutOfHere; expires="+ expDate.toGMTString();
}
//cookie 属性表
/* Here is our "favorite" object.
Properties: fullName - The full descriptive name
cook - The code used for the cookie
urlpath - The full url (http://...) to the site
Methods: Enabled - Returns true if the link's cookie is
turned on
Checked - Returns the word "CHECKED" if the
link's cookie is turned on
WriteAsCheckBox - Sends text to the document in a
checkbox control format
WriteAsWebLink - Sends text to the document in a
<a href...> format
---------------------------------------------------------------* /
function favorite(fullName, cook, urlpath)
{
this.fullName = fullName;
this.cook = cook;
this.urlpath = urlpath;
this.Enabled = Enabled;
this.Checked = Checked;
this.WriteAsCheckBox = WriteAsCheckBox;
this.WriteAsWebLink = WriteAsWebLink;
}
//探测 cookie 的存在
function Enabled()
{
var result = false;
276. var FaveCookie = GetCookie("Favorites");
if (FaveCookie != null)
{
var searchFor = "<" + this.cook + ">";
var startOfCookie = FaveCookie.indexOf(searchFor);
if (startOfCookie != -1)
result = true;
}
return result;
}
function Checked ()
{
if (this.Enabled())
return "CHECKED ";
return "";
}
//设置 cookie.
function WriteAsCheckBox ()
{
// Check to see if it's a title or regular link
if (this.urlpath == "")
{
// It's a section title
result = '<dt><strong>' + this.fullName + '</strong>';
}
else
{
// It's a regular link
result = '<dd><input type="checkbox" name="'+ this.cook + '" '+ this.Checked()+
'onClick="SetFavoriteEnabled(this.name, this.checked);">'+ this.fullName;
}
document.write(result);
}
var NextHeading = "";
function WriteAsWebLink()
{
var result = '';
if (this.urlpath == "")
{
NextHeading = this.fullName; // It's must be a Title
}
else
{
if (this.Enabled() || (GetCookie("ViewAll") == "T"))
277. {
if (NextHeading != "")
{
result = '<p><dt><strong>' + NextHeading+ '</strong>';
NextHeading = "";
}
result = result + '<dd><a href="' + this.urlpath + '">'+ this.fullName + '</a>';
}
}
document.write(result);
}
var FaveList = new Array();
// Comics Section -------------------
FaveList[1] = new favorite("Comics", "", "");
FaveList[2] = new favorite("Dilbert", "cdilb","http://www.unitedmedia.com/comics/dilbert/");
FaveList[3] = new favorite("Doonesbury", "cdoon","http://www.uexpress.com/cgi-
bin/ups/mainindex.cgi?code=db");
FaveList[4] = new favorite("Mr. Boffo", "cboff","http://www.uexpress.com/cgi-
bin/ups/new_mainindex.cgi?code=mb");
// General News Section -------------
FaveList[5] = new favorite("General News", "", "");
FaveList[6] = new favorite("CNN", "ncnn", "http://www.cnn.com/");
FaveList[7] = new favorite("NPR", "nnpr","http://www.npr.org/news/");
FaveList[8] = new favorite("Boston Globe", "nbos","http://www.boston.com/");
// Computer Industry Section --------
FaveList[9] = new favorite("Computer Industry", "", "");
FaveList[10] = new favorite("PC Week", "ipcw","http://www.pcweek.com/");
FaveList[11] = new favorite("TechWeb", "icmp","http://www.techweb.com/wire/wire.html");
FaveList[12] = new favorite("Netscape", "ntsc","http://devedge.netscape.com/");
FaveList[13] = new favorite("Microsoft", "micr","http://msdn.microsoft.com/");
// Search Engines Section -----------
FaveList[14] = new favorite("Search Engines", "", "");
FaveList[15] = new favorite("Yahoo!", "syah","http://www.yahoo.com/");
FaveList[16] = new favorite("Alta Vista", "sav","http://www.altavista.com/");
FaveList[17] = new favorite("Excite", "sexc","http://www.excite.com/");
// Auction Section ------------------
FaveList[18] = new favorite("Auctions", "", "");
FaveList[19] = new favorite("ebay", "ebay","http://www.ebay.com/");
FaveList[20] = new favorite("Yahoo Auctions", "yhac","http://auctions.yahoo.com/");
// Misc. Section --------------------
FaveList[21] = new favorite("Misc.", "", "");
FaveList[22] = new favorite("Today in History", "mtih","http://www.thehistorynet.com/today/
today.htm");
FaveList[23] = new favorite("Merriam-Webster's Word of the Day","mwod", "http://www.m-w.com/
cgi-bin/mwwod.pl");
FaveList[24] = new favorite("Quotes of the Day", "mquot","http://www.starlingtech.com/quotes/
278. qotd.html");
//用户选择
function SendOptionsPage()
{
document.write('<h1>在以下选择 并作为你的珍藏</h1>');
document.write('<form method=post>');
// Here's the button for viewing the Favorites page
document.write('<input type=button value="显示选择的内容" '+ 'onClick="'+'ReloadPage()'+';">');
// The links will look nicer inside a definition listdocument.write('<dl>');
for (var i = 1; i < FaveList.length; i++)
FaveList[i].WriteAsCheckBox();
// Write each checkbox
document.write('</dl><p>');
ClearCookie("ViewAll");
document.write('</form>');
}
//显示
function LoadOptions()
{
SetCookieEZ("ShowOptions", "T");
window.open(document.location.href, "_top", "");
}
function ToggleView()
{
if (GetCookie("ViewAll") == "T")
{
ClearCookie("ViewAll");
}
else
{
var fiveYears = 5 * 365 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime (expDate.getTime() + fiveYears );
SetCookie("ViewAll", "T", expDate, null, null, false);
}
window.open(document.location.href, "_top", "");
}
//显示用户的链接
function SendPersonalPage()
{
if (GetCookie("ViewAll") != "T")
document.write('<h1>你的珍藏:</h1>');
else
279. document.write('<h1>我的链接:</h1>');
// Here are the buttons for viewing the options or
// "View All" pages
document.write('<form method=post>');
if (GetCookie("ViewAll") == "T")
{
document.write('<input type=button value="View Favorites" '+'onClick="ToggleView();">');
}
else
{
document.write('<input type=button value="显示我的珍藏" '+'onClick="ToggleView();">');
}
document.write('<input type=button '+ 'value="点击选择我的珍藏" '+ 'onClick="LoadOptions();
">');
document.write('</form>');
// The links will look nicer inside a definition list
document.write('<dl>');
for (var i = 1; i < FaveList.length; i++)
FaveList[i].WriteAsWebLink(); // Write each link
document.write('</dl><p>');
}
//---------------------------------------------
function isEnabled(name)
{
var result = false;
var FaveCookie = GetCookie("Favorites");
if (FaveCookie != null)
{
var searchFor = "<" + name + ">";
var startOfCookie = FaveCookie.indexOf(searchFor);
if (startOfCookie != -1)
result = true;
}
return result;
}
//---------------------------------------------------------------
//增加数据
function AddFavorite(name)
{
if (!isEnabled(name))
{
var fiveYears = 5 * 365 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime (expDate.getTime() + fiveYears );
SetCookie("Favorites", GetCookie("Favorites")+ "<" + name + ">", expDate, null, null, false);
}
280. }
//---------------------------------------------------------------
//清除用户的设置
function ClearFavorite(name)
{
if (isEnabled(name))
{
var FaveCookie = GetCookie("Favorites");
var searchFor = "<" + name + ">";
var startOfCookie = FaveCookie.indexOf(searchFor);
var NewFaves = FaveCookie.substring(0, startOfCookie)+ FaveCookie.substring(startOfCookie+
searchFor.length,FaveCookie.length);
var fiveYears = 5 * 365 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime (expDate.getTime() + fiveYears );
SetCookie("Favorites", NewFaves, expDate, null, null, false);
}
}
//---------------------------------------------------------------
// 用户设置
function SetFavoriteEnabled(name, SetOn)
{
if (SetOn)
AddFavorite(name);
else
ClearFavorite(name);
}
//---------------------------------------------------------------
//重新载入页面
//---------------------------------------------------------------
function ReloadPage()
{
window.open(document.location.href, "_top", "");
}
// End Commented Script -->
</script>
<title></title>
</head>
<body>
<script language="JavaScript">
<!--
284. 20.5.2 脚 本 详 解
在该程序中 主要是利用脚本来实现的 在设置的脚本中 尽量将 cookie 文件的设
置模块化 希望通过该例的学习 深入的掌握 cookie 文件的属性 方法 同时也逐渐巩
固前面所学的东西 通过这些脚本的设置 希望用户掌握 JavaScript 方面的高级编程的知
识 该程序的脚本设置如下
<script language="JavaScript">
<!--
//显示存在的 cookie.
function GetCookie(name)
{
var result = null;
var myCookie = " " + document.cookie + ";";
var searchName = " " + name + "=";
var startOfCookie = myCookie.indexOf(searchName);
var endOfCookie;
if (startOfCookie != -1)
{
startOfCookie += searchName.length;
// skip past cookie name
endOfCookie = myCookie.indexOf(";", startOfCookie);
result = unescape(myCookie.substring(startOfCookie,endOfCookie));
}
return result;
}
//设置 cookie.
function SetCookieEZ(name, value)
{
document.cookie = name + "=" + escape(value);
}
function SetCookie(name, value, expires, path, domain, secure)
{
var expString = ((expires == null)? "" : ("; expires=" + expires.toGMTString()));
var pathString = ((path == null) ? "" : ("; path=" + path));
var domainString = ((domain == null)? "" : ("; domain=" + domain));
var secureString = ((secure == true) ? "; secure" : "");
document.cookie = name + "=" + escape(value)+ expString + pathString + domainString+
secureString;
}
//清除 cookie.
function ClearCookie(name)
285. {
var ThreeDays = 3 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime (expDate.getTime() - ThreeDays);
document.cookie = name + "=ImOutOfHere; expires="+ expDate.toGMTString();
}
//cookie 属性表
/* Here is our "favorite" object.
Properties: fullName - The full descriptive name
cook - The code used for the cookie
urlpath - The full url (http://...) to the site
Methods: Enabled - Returns true if the link's cookie is
turned on
Checked - Returns the word "CHECKED" if the
link's cookie is turned on
WriteAsCheckBox - Sends text to the document in a
checkbox control format
WriteAsWebLink - Sends text to the document in a
<a href...> format
---------------------------------------------------------------* /
function favorite(fullName, cook, urlpath)
{
this.fullName = fullName;
this.cook = cook;
this.urlpath = urlpath;
this.Enabled = Enabled;
this.Checked = Checked;
this.WriteAsCheckBox = WriteAsCheckBox;
this.WriteAsWebLink = WriteAsWebLink;
}
//探测 cookie 的存在
function Enabled()
{
var result = false;
var FaveCookie = GetCookie("Favorites");
if (FaveCookie != null)
{
var searchFor = "<" + this.cook + ">";
var startOfCookie = FaveCookie.indexOf(searchFor);
if (startOfCookie != -1)
result = true;
}
return result;
}
function Checked ()
286. {
if (this.Enabled())
return "CHECKED ";
return "";
}
//设置 cookie.
function WriteAsCheckBox ()
{
// Check to see if it's a title or regular link
if (this.urlpath == "")
{
// It's a section title
result = '<dt><strong>' + this.fullName + '</strong>';
}
else
{
// It's a regular link
result = '<dd><input type="checkbox" name="'+ this.cook + '" '+ this.Checked()+
'onClick="SetFavoriteEnabled(this.name, this.checked);">'+ this.fullName;
}
document.write(result);
}
var NextHeading = "";
function WriteAsWebLink()
{
var result = '';
if (this.urlpath == "")
{
NextHeading = this.fullName; // It's must be a Title
}
else
{
if (this.Enabled() || (GetCookie("ViewAll") == "T"))
{
if (NextHeading != "")
{
result = '<p><dt><strong>' + NextHeading+ '</strong>';
NextHeading = "";
}
result = result + '<dd><a href="' + this.urlpath + '">'+ this.fullName + '</a>';
}
}
document.write(result);
}
287. var FaveList = new Array();
// Comics Section -------------------
FaveList[1] = new favorite("Comics", "", "");
FaveList[2] = new favorite("Dilbert", "cdilb","http://www.unitedmedia.com/comics/dilbert/");
FaveList[3] = new favorite("Doonesbury", "cdoon","http://www.uexpress.com/cgi-
bin/ups/mainindex.cgi?code=db");
FaveList[4] = new favorite("Mr. Boffo", "cboff","http://www.uexpress.com/cgi-
bin/ups/new_mainindex.cgi?code=mb");
// General News Section -------------
FaveList[5] = new favorite("General News", "", "");
FaveList[6] = new favorite("CNN", "ncnn", "http://www.cnn.com/");
FaveList[7] = new favorite("NPR", "nnpr","http://www.npr.org/news/");
FaveList[8] = new favorite("Boston Globe", "nbos","http://www.boston.com/");
// Computer Industry Section --------
FaveList[9] = new favorite("Computer Industry", "", "");
FaveList[10] = new favorite("PC Week", "ipcw","http://www.pcweek.com/");
FaveList[11] = new favorite("TechWeb", "icmp","http://www.techweb.com/wire/wire.html");
FaveList[12] = new favorite("Netscape", "ntsc","http://devedge.netscape.com/");
FaveList[13] = new favorite("Microsoft", "micr","http://msdn.microsoft.com/");
// Search Engines Section -----------
FaveList[14] = new favorite("Search Engines", "", "");
FaveList[15] = new favorite("Yahoo!", "syah","http://www.yahoo.com/");
FaveList[16] = new favorite("Alta Vista", "sav","http://www.altavista.com/");
FaveList[17] = new favorite("Excite", "sexc","http://www.excite.com/");
// Auction Section ------------------
FaveList[18] = new favorite("Auctions", "", "");
FaveList[19] = new favorite("ebay", "ebay","http://www.ebay.com/");
FaveList[20] = new favorite("Yahoo Auctions", "yhac","http://auctions.yahoo.com/");
// Misc. Section --------------------
FaveList[21] = new favorite("Misc.", "", "");
FaveList[22] = new favorite("Today in History",
"mtih","http://www.thehistorynet.com/today/today.htm");
FaveList[23] = new favorite("Merriam-Webster's Word of the Day","mwod", "http://www.m-
w.com/cgi-bin/mwwod.pl");
FaveList[24] = new favorite("Quotes of the Day",
"mquot","http://www.starlingtech.com/quotes/qotd.html");
//===============================================================
// Page Writing Routines
//===============================================================
//---------------------------------------------------------------
// SendOptionsPage - Writes a page allowing the user to select
// her favorite preferences
//---------------------------------------------------------------
function SendOptionsPage()
{
document.write('<h1>在以下选择并作为你的珍藏</h1>');
288. document.write('<form method=post>');
// Here's the button for viewing the Favorites page
document.write('<input type=button value="显示选择的内容" '+
'onClick="'+'ReloadPage()'+';">');
// The links will look nicer inside a definition listdocument.write('<dl>');
for (var i = 1; i < FaveList.length; i++)
FaveList[i].WriteAsCheckBox();
// Write each checkbox
document.write('</dl><p>');
ClearCookie("ViewAll");
document.write('</form>');
}
//---------------------------------------------------------------
// LoadOptions - Sets the ShowOptions cookie, which makes the
// option selection page appear when the page is
// then reloaded.
//---------------------------------------------------------------
function LoadOptions()
{
SetCookieEZ("ShowOptions", "T");
window.open(document.location.href, "_top", "");
}
function ToggleView()
{
if (GetCookie("ViewAll") == "T")
{
ClearCookie("ViewAll");
}
else
{
var fiveYears = 5 * 365 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime (expDate.getTime() + fiveYears );
SetCookie("ViewAll", "T", expDate, null, null, false);
}
window.open(document.location.href, "_top", "");
}
//---------------------------------------------------------------
// SendPersonalPage - Writes a page showing the categories and
// links which the user prefers. Only shows a
// heading if one of its favorites is enabled
//---------------------------------------------------------------
function SendPersonalPage()
{
if (GetCookie("ViewAll") != "T")
289. document.write('<h1>你的珍藏:</h1>');
else
document.write('<h1>我的链接:</h1>');
// Here are the buttons for viewing the options or
// "View All" pages
document.write('<form method=post>');
if (GetCookie("ViewAll") == "T")
{
document.write('<input type=button value="显示" '+'onClick="ToggleView();">');
}
else
{
document.write('<input type=button '+ ' value="显示的珍藏" '+'onClick="ToggleView();">');
}
document.write('<input type=button '+ 'value="点击选择显示我的珍藏 " '+
'onClick="LoadOptions();">');
document.write('</form>');
// The links will look nicer inside a definition list
document.write('<dl>');
for (var i = 1; i < FaveList.length; i++)
FaveList[i].WriteAsWebLink(); // Write each link
document.write('</dl><p>');
}
//===============================================================
// Helper Functions
//===============================================================
//---------------------------------------------------------------
// isEnabled - Returns True if the favorite identified by the
// name parameter is enabled.
//---------------------------------------------------------------
function isEnabled(name)
{
var result = false;
var FaveCookie = GetCookie("Favorites");
if (FaveCookie != null)
{
var searchFor = "<" + name + ">";
var startOfCookie = FaveCookie.indexOf(searchFor);
if (startOfCookie != -1)
result = true;
}
return result;
}
function AddFavorite(name)
{
if (!isEnabled(name))
290. {
var fiveYears = 5 * 365 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime (expDate.getTime() + fiveYears );
SetCookie("Favorites", GetCookie("Favorites")+ "<" + name + ">", expDate, null, null, false);
}
}
function ClearFavorite(name)
{
if (isEnabled(name))
{
var FaveCookie = GetCookie("Favorites");
var searchFor = "<" + name + ">";
var startOfCookie = FaveCookie.indexOf(searchFor);
var NewFaves = FaveCookie.substring(0, startOfCookie)+
FaveCookie.substring(startOfCookie+searchFor.length,FaveCookie.length);
var fiveYears = 5 * 365 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime (expDate.getTime() + fiveYears );
SetCookie("Favorites", NewFaves, expDate, null, null, false);
}
}
function SetFavoriteEnabled(name, SetOn)
{
if (SetOn)
AddFavorite(name);
else
ClearFavorite(name);
}
function ReloadPage()
{
window.open(document.location.href, "_top", "");
}
// End Commented Script -->
</script>
<script language="JavaScript">
<!--
if (GetCookie("ShowOptions") == "T")
{
ClearCookie("ShowOptions");
SendOptionsPage();
291. }
else
{
SendPersonalPage();
}
// End Commented Script -->
</script>
其中各个函数介绍如下
1 getcookie 函 数
该函数用来获得要检索的 cookie 值 在该脚本中 设置了一系列的变量来截取 cookie
值 最后 返回一个函数值来供其他的函数脚本调用
为了方便函数的调用 在设置的函数中 设置了一个 name 参数
该函数的脚本如下
function GetCookie(name)
{
var result = null;
var myCookie = " " + document.cookie + ";";
var searchName = " " + name + "=";
var startOfCookie = myCookie.indexOf(searchName);
var endOfCookie;
if (startOfCookie != -1)
{
startOfCookie += searchName.length;
endOfCookie = myCookie.indexOf(";", startOfCookie);
result = unescape(myCookie.substring(startOfCookie,endOfCookie));
}
return result;
}
其中
function GetCookie(name) 设置函数 传递一个 name 的 arg 参数
var result = null 设置变量 设置变量的值为空
var myCookie = " " + document.cookie + ";" 取得文档的 cookie 值 并将它
赋给设置的参数 mycookie
var searchName = " " + name + "=" 设置检索参数
var startOfCookie = myCookie.indexOf(searchName) 调用字符串对象的
indexof()函数在设置的 cookie 对象中查看检索对象是否存在 如果该对象存在
就返回该字符串在 cookie 文件中的位置值 如果不存在则返回一个-1 值 最后
将检索到的值赋给设置的变量
var endOfCookie 设置变量
if (startOfCookie != -1) 如果不存在检索对象
startOfCookie += searchName.length 重新设置检索函数值 这里设置的是
检索字段的起始位置
307. <p align="center"><font face=" 楷 体 _GB2312" color="#0000FF"><big><big><big><big> 日 历
</big></big></big></big></font></p>
<form name="clock">
<div align="center"><center><p><input type="text" name="disp" value size="20"> <br>
</p>
</center></div>
</form>
<script LANGUAGE="JavaScript">
<!--
function getTime() {
// initialize time-related variables with current time settings
var now = new Date()
var hour = now.getHours()
var minute = now.getMinutes()
now = null
var ampm = ""
// validate hour values and set value of ampm
if (hour >= 12) {
hour -= 12
ampm = "下午"
} else
ampm = "上午"
hour = (hour == 0) ? 12 : hour
// add zero digit to a one digit minute
if (minute < 10)
minute = "0" + minute // do not parse this number!
// return time string
return hour + ":" + minute + " " + ampm
}
function leapYear(year) {
if (year % 4 == 0) // basic rule
return true // is leap year
/* else */ // else not needed when statement is "return"
return false // is not leap year
}
function getDays(month, year) {
// create array to hold number of days in each month
var ar = new Array(12)
ar[0] = 31 // January
ar[1] = (leapYear(year)) ? 29 : 28 // February
308. ar[2] = 31 // March
ar[3] = 30 // April
ar[4] = 31 // May
ar[5] = 30 // June
ar[6] = 31 // July
ar[7] = 31 // August
ar[8] = 30 // September
ar[9] = 31 // October
ar[10] = 30 // November
ar[11] = 31 // December
// return number of days in the specified month (parameter)
return ar[month]
}
function getMonthName(month) {
// create array to hold name of each month
var ar = new Array(12)
ar[0] = "1 月"
ar[1] = "2 月"
ar[2] = "3 月"
ar[3] = "4 月"
ar[4] = "5 月"
ar[5] = "6 月"
ar[6] = "7 月"
ar[7] = "8 月"
ar[8] = "9 月"
ar[9] = "10 月"
ar[10] = "11 月"
ar[11] = "12 月"
// return name of specified month (parameter)
return ar[month]
}
function setCal() {
// standard time attributes
var now = new Date()
var year = now.getYear()
var month = now.getMonth()
var monthName = getMonthName(month)
var date = now.getDate()
now = null
// create instance of first day of month, and extract the day on which it occurs
var firstDayInstance = new Date(year, month, 1)
var firstDay = firstDayInstance.getDay()
firstDayInstance = null
309. // number of days in current month
var days = getDays(month, year)
// call function to draw calendar
drawCal(firstDay + 1, days, date, monthName, 1900 + year)
}
function drawCal(firstDay, lastDate, date, monthName, year) {
// constant table settings
var headerHeight = 50 // height of the table's header cell
var border = 2 // 3D height of table's border
var cellspacing = 4 // width of table's border
var headerColor = "midnightblue" // color of table's header
var headerSize = "-1" // size of tables header font
var colWidth = 50// width of columns in table
var dayCellHeight = 10 // height of cells containing days of the week
var dayColor = "darkblue" // color of font representing week days
var cellHeight = 20// height of cells representing dates in the calendar
var todayColor = "red" // color specifying today's date in the calendar
var timeColor = "purple" // color of font representing current time
// create basic table structure
var now = new Date()
var year = now.getYear()
var text = "" // initialize accumulative variable to empty string
text += '<CENTER>'
text += '<TABLE BORDER=1' + ' CELLSPACING=0' + 'style="font-size: 9pt">' // table
settings
text += '<TH COLSPAN=7 HEIGHT=' + headerHeight + '>' // create table header cell
text += '' // set font for table header
text +=year+'年'+ monthName + '日历'
text += '' // close table header's font settings
text += '</TH>' // close header cell
// variables to hold constant settings
var openCol = '<TD WIDTH=' + colWidth + ' HEIGHT=' + dayCellHeight + '>'
openCol += '<FONT COLOR="' + dayColor + '">'
var closeCol = '</FONT></TD>'
// create array of abbreviated day names
var weekDay = new Array(7)
weekDay[0] = "星期天"
weekDay[1] = "星期一"
weekDay[2] = "星期二"
weekDay[3] = "星期三"
weekDay[4] = "星期四"
310. weekDay[5] = "星期五"
weekDay[6] = "星期六"
// create first row of table to set column width and specify week day
text += '<TR ALIGN="center" VALIGN="center" style="font-size: 9pt">'
for (var dayNum = 0; dayNum < 7; ++dayNum) {
text += openCol + weekDay[dayNum] + closeCol
}
text += '</TR>'
// declaration and initialization of two variables to help with tables
var digit = 1
var curCell = 1
for (var row = 1; row <= Math.ceil((lastDate + firstDay - 1) / 7); ++row) {
text += '<TR ALIGN="right" VALIGN="top" style="font-size: 9pt">'
for (var col = 1; col <= 7; ++col) {
if (digit > lastDate)
break
if (curCell < firstDay) {
text += '<TD></TD>';
curCell++
} else {
if (digit == date) { // current cell represent today's date
text += '<TD HEIGHT=1>'
text += '<FONT COLOR="' + todayColor + '">'
text += digit
text += '</FONT><BR>'
text += '<FONT COLOR="' + timeColor + '" SIZE=2 style="font-size: 9pt">'
text += '<CENTER>' + getTime() + '</CENTER>'
text += '</FONT>'
text += '</TD>'
} else
text += '<TD HEIGHT=' + cellHeight + '>' + digit + '</TD>'
digit++
}
}
text += '</TR>'
}
// close all basic table tags
text += '</TABLE>'
text += '</CENTER>'
// print accumulative HTML string
document.write(text)
}
// -->
335. 图22-117
22.67 实 例 学 习
在学习了 ASP 的基础知识后 下面举一个简单的实例 实现服务端页面的交互 收
集用户的信息 并将用户填写的数据传递给用户
程序的源代码下
query.asp 脚本源代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>网络调查</title>
</head>
<body>
<%
response.write"<br><big><strong><blink>请检查填写的数据 </blink></strong></big>"
if request.form("name")<>"" then
response.write"<br>你的姓名是 "&request.form("name")
else
response.write"<br>你还没有填写姓名呢 请你填写姓名 "
end if
if request.form("address")<>"" then
response.write"<br>你的地址为 "&request.form("address")
else
response.write"<br>你还没有填写地址呢 请填写 "
336. end if
response.write"<br>你的性别为 "
if request.form("sex")="man" then
response.write"男"
else
response.write"女"
end if
age=""
select case request.form("age")
case 0: age="18 岁以下"
case 1: age="18-25 岁"
case 2: age="26-35 岁"
case 3: age="36-45 岁"
case 4: age="46-65 岁"
case 5: age="66 岁以上"
end select
response.write"<br>你的年龄为 "&age
for i=1 to request.form("city").count
if request.form("city")<>"" then
response.write"<br>你要去的城市为 "
if request.form("city")(i)="beijing" then
response.write"北京"
end if
else if request.form("city")(i)="shanghai" then
response.write"上海"
else
response.write"其他城市"
end if
end if
next
if request.form("brief")<>"" then
response.write"<br>你的简短留言 "&request.form("brief")
end if
%>
</body>
</html>
Query.htm 源代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>国庆旅游网上调查</title>
<meta name="GENERATOR" content="Microsoft FrontPage 3.0">
<script language="JavaScript"><!--
function isrequired(thefield)
{
if( thefield.value=="")
346. 4 Onsubmit 事件处理器
该事件处理器用来处理当用户提交表单的时候 调用设置的函数或系统预定义的方法
处理表单的输入或选择 在该脚本中 设置当用户按下提交按钮的时候 调用设置的函数
queren 检查用户是否填写了数据
该事件的设置一般位于<form >中
<form method="POST" name="query"
onsubmit="queren()" action="query.asp">
22.69.3 服务端脚本详解
在 query.asp 页面中 设置了处理用户输入的数据 脚本代码如下
<html>
<head>
<title>网络调查</title>
</head>
<body>
<%
response.write"<br><big><strong><blink>请检查填写的数据 </blink></strong></big>"
if request.form("name")<>"" then
response.write"<br>你的姓名是 "&request.form("name")
else
response.write"<br>你还没有填写姓名呢 请你填写姓名 "
end if
if request.form("address")<>"" then
response.write"<br>你的地址为 "&request.form("address")
else
response.write"<br>你还没有填写地址呢 请填写 "
end if
response.write"<br>你的性别为 "
if request.form("sex")="man" then
response.write"男"
else
response.write"女"
end if
age=""
select case request.form("age")
case 0: age="18 岁以下"
case 1: age="18-25 岁"
case 2: age="26-35 岁"
case 3: age="36-45 岁"
case 4: age="46-65 岁"
case 5: age="66 岁以上"
347. end select
response.write"<br>你的年龄为 "&age
for i=1 to request.form("city").count
if request.form("city")<>"" then
response.write"<br>你要去的城市为 "
if request.form("city")(i)="beijing" then
response.write"北京"
end if
else if request.form("city")(i)="shanghai" then
response.write"上海"
else
response.write"其他城市"
end if
end if
next
if request.form("brief")<>"" then
response.write"<br>你的简短留言 "&request.form("brief")
end if
%>
</body>
</html>
其中
<% 设置 asp 文件的标志 前面已经讲过 asp 文件一般是放在<%%>之间
response.write"<br><big><strong><blink>请检查填写的数据 /blink> </strong>
</big>" response 设置用户输出数据 该语句设置输入主体的格式 提示用户
检查填写的数据
if request.form("name")<>"" then 典型的 asp 文件应用格式 该语句用来判
断用户是否输入了数据 其中 request.form() 当用户设置的表单的传递方法为
post 的时候 利用该语句取得用户输入的数据 其中 name 设置一个数组
坐标 告诉 asp 文档 取得值为用户设置的姓名文本框的值 如果用户输入的数
据不为空 则执行如下的语句
response.write"<br> 你 的姓名是 "&request.form("name") 调 用 response
对象的 write 方法 在新文档中写入数据 这里写入的数据为用户在起始页面设
置的姓名文本框的值 request.form("name")
else 如果用户没有输入数据
response.write"<br>你还没有填写姓名呢 请你填写姓名 " 在利用 asp 产生的
文档中写入提示信息 让用户写入数据
end if 该语句结束判断 在 asp 页面编程中 语句的设置和检查是相当严格的
if 和 end if 的配套是要一一匹配的 有 if 就必有 end if 来结束
if request.form("address")<>"" then 该语句的意义同上 只是这里设置的是
用户的地址值 在这里提醒用户的是 在设置了 if 语句后 一定要跟一个 then
关键字 否则在调试程序的时候就会报错
348. response.write"<br>你 的地 址 为 "&request.form("address") 在 新文档 中写入
用户填写的数据:用户的地址
else 如果用户没有输入地址这样的数据
response.write"<br>你还没有填写地址呢 请填写 " 如果用户没有输入地址
数据 提示用户没有输入地址数据 请用户填写相应的数据
end if 结束该语句的判断 如果不跟这样的语句来结束用户的定义 系统就会
报错
以上向我们提供了服务器端数据校验的模式 用户在处理表单的过程中 可以直接按
照上面的格式套用 事实上 客户端 服务器端数据的处理的原理都差不多 只是在设置
的过程中调用的语句不同罢了
response.write"<br>你的性别为 " 在新文档中写入用户的数据 用户选择的性
别
if request.form("sex")="man" then 这里做这样的处理 主要是考虑到中文用
户 设置的页面也为中文的字体 该语句来获得用户的性别值 如果用户设置的
性别值为 man 的话 那么就在文档中输入数据 男
response.write"男" 在新文档中输入 男
else 如果用户设置的性别值为其他数据的话
response.write"女" 在新文档中输入 女
end if 结束这一模块的定义
以上的格式 向我们展示了如何处理外文格式为用户所在环境支持的格式 这里将用
户不熟悉的英文格式统一为用户熟悉的中文格式环境
age="" 设置一个 age 的字符串变量 定义这样的变量 主要是为了处理用户选
择的年龄
select case request.form("age") 该语句利用 select case 判断用户选择的年
龄 利用该语句来判断设置条件较多的时候 取代 if 语句 以使语句简洁 程序
更具可读性
case 0: age="18 岁以下" 表示如果用户选择了第一个选项 则系统获得一个
值 这时再返回去 显示系统选择的第一项值 将 age 值设置为 18 岁以下
case 1: age="18-25 岁" 如果 request.form("age")返回一个值为 1 则将该值所
代表的年龄的值赋给 age 这里年龄的值为 18-25 岁
case 2: age="26-35 岁" 如果 request.form("age")返回一个值为 2 则将该值所
代表的年龄的值赋给 age 这里年龄的值为 26-35 岁
case 3: age="36-45 岁" 如果 request.form("age")返回一个值为 3 则将该值所
代表的年龄的值赋给 age 这里年龄的值为 36-45 岁
case 4: age="46-65 岁" 如果 request.form("age")返回一个值为 4 则将该值所
代表的年龄的值赋给 age 这里年龄的值为 46-65 岁
case 5: age="66 岁以上" 如果 request.form("age")返回一个值为 5 则将该值
所代表的年龄的值赋给 age 这里年龄的值为 66 岁以上
end select 结束 select case 的设置
response.write"<br>你的年龄为 "&age 在新文档中写入用户选择的年龄段
349. 显示用户的年龄数目
for i=1 to request.form("city").count 设置循环 request.form("city").count
取得用户设置的复选框的个数
if request.form("city")<>"" then 如果用户选取了设置的复选框 这样就会返
回一个值 该语句就是判断用户是否选择了复选框其中之一
response.write"<br>你要去的城市为 " 如果用户选择了 就显示用户显示的
信息 由于页面的设计者设置的是获取用户的去向信息 所以我们知道用户是在
选择用户要去的城市 所以 在新文档中写入文本用户要去的城市
考虑到国内用户的习惯 以下的语句将设置的英文值转换为中文值
if request.form("city")(i)="beijing" then 如果表单返回的值为 Beijing 即
用户选择的是去北京的话 则写入 北京 两个字
response.write"北京" 在新文档中写入北京两个字
end if 结束一个 if 语句的设置
else if request.form("city")(i)="shanghai" then 这一句的意义功能同上 只是注
意这里 else if 的利用
response.write"上海" 写入 上海
else 同上面的 if 语句相对 设置意外的情况
response.write "其他城市" 写入其他城市的提示
end if 结束中文文档转换的设置
end if 结束用户选择要去城市的设置
next 继续循环 直到循环条件的结束
if request.form("brief")<>"" then 该语句获取用户输入的简短留言
response.write"<br>你的简短留言 "&request.form("brief") 在新文档中写入用
户设置的简短留言
end if 结束该模块的设置
%> asp 语句模块结束的标志 在前面已经讲了 asp 语句以 <% 开始 以
%> 语句结束