ASP.NET学习笔记十二之AJAX

  • 创建AJAX对象

清单 3. 在 Microsoft 浏览器上创建 XMLHttpRequest 对象

var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}

 

清单 1.在支持AJAX的非Microsoft浏览器上创建XMLHttpRequest对象

var xmlHttp = new XMLHttpRequest object;

 

清单 4. 以支持多种浏览器的方式创建 XMLHttpRequest 对象

/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
@end @*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}

 

Ajax 世界中的请求/响应

发出请求

 

从 Web 表单中获取需要的数据。
建立要连接的 URL。
打开到服务器的连接。
设置服务器在完成后要运行的函数。
发送请求。

 

清单 5 中的示例 Ajax 方法就是按照这个顺序组织的:

清单 5. 发出 Ajax 请求

function callServer() {
// Get the city and state from the web form
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;  //从表单获取数据
// Only go on if there are values for both fields
if ((city == null) || (city == "")) return;
if ((state == null) || (state == "")) return;
// Build the URL to connect to
var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);  //创建url
// Open a connection to the server
xmlHttp.open("GET", url, true);  //参数三为true,表示异步传输
// Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = updatePage;   //疑问
// Send the request
xmlHttp.send(null);   //疑问
}

 

处理响应

 

什么也不要做,直到 xmlHttp.readyState 属性的值等于 4。
服务器将把响应填充到 xmlHttp.responseText 属性中。

其中的第一点,即就绪状态,将在下一篇文章中详细讨论,您将进一步了解 HTTP 请求的阶段,可能比您设想的还多。现在只要检查一个特定的值(4)就可以了(下一期文章中还有更多的值要介绍)。第二点,使用 xmlHttp.responseText 属性获得服务器的响应,这很简单。清单 6 中的示例方法可供服务器根据 清单 5 中发送的数据调用。

 

清单 6. 处理服务器响应

function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("zipCode").value = response;
}
}

 

清单 7. 启动一个 Ajax 过程

<form>
 <p>City: <input type="text" name="city" id="city" size="25" 
       onChange="callServer();" /></p>
 <p>State: <input type="text" name="state" id="state" size="25" 
       onChange="callServer();" /></p>
 <p>Zip Code: <input type="text" name="zipCode" id="city" size="5" /></p>
</form>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值