XMLHttpRequest 对象用于在后台与服务器交换数据。
创建 XMLHttpRequest 对象
所有现代浏览器 (IE7+、Firefox、Chrome、Safari 以及 Opera) 都内建了 XMLHttpRequest 对象。
通过一行简单的 JavaScript 代码,我们就可以创建 XMLHttpRequest 对象。
创建 XMLHttpRequest 对象的语法:
xmlhttp=new XMLHttpRequest();
老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
实例
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <script>
- var xmlHttp;
- //判断老版本浏览器使用使用 ActiveX 对象
- var Try = {
- these: function() {
- var returnValue;
- for (var i = 0; i < arguments.length; i++) {var lambda = arguments[i]; try {returnValue = lambda(); break;} catch (e) {}}
- return returnValue;
- }
- }
- function makeRequest(queryString, php, func, method) {
- xmlHttp = Try.these(
- function() {return new XMLHttpRequest()},
- function() {return new ActiveXObject('Msxml2.XMLHTTP')},
- function() {return new ActiveXObject('Microsoft.XMLHTTP')}
- );
- method = (typeof method == 'undefined') ? 'post' : 'get';
- if(func) xmlHttp.onreadystatechange = eval(func);
- xmlHttp.open(method, queryString, true);
- xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
- xmlHttp.send(method == 'post' ? queryString : null);
- }
-
- get_letter();
- function get_letter() {
- makeRequest('update.php', '?', '_get_letter');
- }
- function _get_letter() {
- if(xmlHttp.readyState==4 && xmlHttp.status==200) {
- if(xmlHttp.responseText) {
- alert(xmlHttp.responseText);
- }
- }
- }
-
- </script>
- </head>
- <body>
- </body>
- </html>
|