Ajax(二):技术实现
一.若没有Ajax时,一般的表单提交代码为:
客户端代码
<form id="form1" action="Test.ashx" method="get">
您的姓名1:<input type="text" name="fname" size="20" />
<input type="submit" name="submit" value="Sumbit">
</form>
服务端代码
public void ProcessRequest (HttpContext context)
{
//Delay
for (int i = 0; i < 2; i++)
{
System.Threading.Thread.Sleep(1000);
}
//从Requset.Form中获取fname的值。使用Form获取请求的键值对的值的前提条件是HTTP request Content-Type 值必须是"application/x-www-form-urlencoded" 或 "multipart/form-data".
string fname = context.Request["fname"];
context.Response.ContentType = "text/plain";
//将字符串写入 HTTP 响应输出流。
context.Response.Write("Hello World " + fname);
}
此时的工作流程为:
二.Ajax代码:
客户端代码:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="Ajax.js"></script>
</head>
<body>
<div id="Test" style="background-color:#40eeee">
您的姓名2:<input type="text" id="testGetName" size="20" />
<button type="button" onclick="testGet();">Ajax Get请求</button>
</div>
<div id="Test" style="background-color:#ff6a00">
您的姓名3:<input type="text" id="testPostName" size="20" />
<button type="button" onclick="testPost();">Ajax Post请求</button>
</div>
<div id="myDiv" />
</body>
</html>
客户端JS代码:
var xmlhttp = createRequest();
function testGet() {
var fname = document.getElementById("testGetName").value;
xmlhttp.open("GET", "Test.ashx?fname=" + fname + "&random=" + Math.random() , true);
xmlhttp.onreadystatechange = callback;
xmlhttp.send(null);
}
function testPost() {
var fname = document.getElementById("testPostName").value;
xmlhttp.open("POST", "Test.ashx?" + "&random=" + Math.random() , true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.onreadystatechange = callback;
xmlhttp.send("fname="+fname);
}
function createRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp
}
function callback() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
此时的工作流程为: