笔记1中程序的缺陷:
new ActiveXObject("Microsoft.XMLHTTP") 是 IE 中创建 XMLHttpRequest对 象的方法。非 IE 浏览器中创建方法是 new XmlHttpRequest() 。 为了兼容不同的浏览器需要编写很多代码。
JQuery AJAX改进:
JQuery 中提供了简化 ajax 使用的方法。 $.ajax() 函数是 JQuery 中提供的ajax 访问函数, $.post() 是对 $.ajax() 的 post 方式提交 ajax 查询的封装, $.get() 是对 $.ajax() 的 get 方式提交 ajax 查询的封装。推荐用 post 方式,因为 post 方式没有缓存的问题,演示, get 方式中缓存处理的处理方法。
案例:JQuery AJAX版本的获取服务器时间
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
function btnClick() {
// 回调函数中 data 参数为服务器返回的数据, textStatus 为服务器返回状态码, textStatus 为 "success" 表示成功。
$.post("GetDate1.ashx", function (data, textStatus) {//第一个参数:服务器返回的数据,第二个参数:服务器执行的状态
if (textStatus == "success") {
$("#Text1").val(data);
}
else {
alert("AJAX服务器返回失败!");
}
});
}
</script>
</head>
<body>
<input id="Text1" type="text" />
<input id="btnPost" type="button" value="获取时间" onclick="btnClick()"/>
</body>
</html>
案例: JQuery AJAX 版的汇率转换。注意 status 指的是通讯是否成功
如果有请求参数则在第二个参数用字典方式来设置。$.post("money.ashx", { "amount": amount, "moneytype": moneytype}, function (data, textStatus) {。 JQuery帮我们进行了 URL 编码,因此参数中有中文也不用担心。
服务器端:money.ashx
<%@ WebHandler Language="C#" Class="money" %>
using System;
using System.Web;
public class money : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string amount = context.Request["amount"];
string moneytype = context.Request["moneytype"];
int Smount = Convert.ToInt32(amount);
if (moneytype == "1")//美元
{
context.Response.Write(Smount/7);
}
else if (moneytype == "2")//日元
{
context.Response.Write(Smount*10);
}
else if (moneytype == "3")//港币
{
context.Response.Write(Smount*10/9);
}
}
public bool IsReusable {
get {
return false;
}
}
}
客户端:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function Button1_onclick() {
var amount = $("#Text1").val();
var moneytype = $("#Select1").val();
$.post("money.ashx", { "amount": amount, "moneytype": moneytype}, function (data, textStatus) {//第一个参数:服务器返回的数据,第二个参数:服务器执行的状态
if (textStatus == "success") {
$("#Text2").val(data);
}
else {
alert("AJAX服务器返回失败!");
}
});
}
</script>
</head>
<body>
<input id="Text1" type="text" />
<select id="Select1">
<option value="1">美元</option>
<option value="2">日元</option>
<option value="3">港币</option>
</select>
<input id="Button1" type="button" value="button" onclick="return Button1_onclick()" />
<input id="Text2" type="text" />
</body>
</html>