一张html静态网页和一张aspx动态网页就构成了Ajax所需要的两张网页。其中html网页中存放javascript代码和html代码,javascript用于和服务器通信而html则用于构成网页页面;剩下的一张aspx页面就是服务器中响应客户端javascript的。
我做了一个简单的例子:aspx动态页面代码中获取客户端文本框(txt)中内容然后将txt中的文本和服务器端时间反应到客户端。说白了,就是"txt文本"+"服务器端"时间。
html网页
1
<html xmlns="http://www.w3.org/1999/xhtml">
2
<head>
3
<title>Javascript</title>
4
5
<script language="javascript" type="text/javascript">
6
var xmlHttp = false;
7
8
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
9
xmlHttp = new XMLHttpRequest();
10
}
11
12
function callServer() {
13
var txt = document.getElementsByName("txt").item(0).value;
14
var url = "Default2.aspx?txt=" + escape(txt);
15
xmlHttp.open("GET", url, true);
16
xmlHttp.onreadystatechange = updatePage;
17
xmlHttp.send(null);
18
}
19
20
function updatePage() {
21
if (xmlHttp.readyState == 4) {
22
var response = xmlHttp.responseText;
23
document.getElementById("div1").innerHTML = response;
24
}
25
}
26
</script>
27
28
</head>
29
<body>
30
<div id="div1" style="background-color: Yellow">test text.</div>
31
<input name="txt" value="hello" />
32
<input value="提交" type="button" onclick="callServer()" />
33
</body>
34
</html>

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

Default2.aspx中代码
1
<%@ Page Language="C#" %>
2
<%
3
Response.Write(Request["txt"] +": " + System.DateTime.Now.ToString());
4
%>

2

3

4

每次在浏览器点击”提交“按钮,都会显示服务器端时间,无页面刷新。