如何不用jQuery仅用AJAX技术实现网页数据交互?
- 内容介绍
- 文章标签
- 相关推荐
本文共计466个文字,预计阅读时间需要2分钟。
javascript// 创建一个Ajax对象function createAjax() { var xhr; if (window.XMLHttpRequest) { xhr=new XMLHttpRequest(); } else { xhr=new ActiveXObject(Microsoft.XMLHTTP); } return xhr;}
// 连接服务器function connectServer(url, method, data, callback) { var xhr=createAjax(); xhr.onreadystatechange=function() { if (xhr.readyState==4 && xhr.status==200) { callback(xhr.responseText); } }; xhr.open(method, url, true); xhr.setRequestHeader(Content-Type, application/x-www-form-urlencoded); xhr.send(data);}
// 使用示例connectServer(http://example.com/api/data, POST, key=value, function(response) { console.log(response);});
gistfile1.txtajax的简易编写大致分为四个部分 创建一个Ajax对象,连接服务器,发送请求,接收返回值 在创建对象的时候有一个兼容的问题,IE6不兼容XMLHttpRequest(),因此用if语句进行判断 if(window.XMLHttpRequest) { var oAjax=new XMLHttpRequest(); } else { var oAjax=new ActiveXObject("Microsoft.XMLHTTP"); } 第二步连接服务器 用open方法,open(方法(get/post),文件名,异步传输),在这里可以有一,个清除缓存:缓存是通过url来的,只要让url不停地改变就可以清除缓存,把路径改为 "url?t="+new Date().getTime() 第三部发送请求,直接send() 第四部接收需要判断, readystate属性:请求状态: 0,未调用open() 1,载入send() 2,完成载入send() 3,解析 4,完成 status:完成状态 200-成功,其他失败
本文共计466个文字,预计阅读时间需要2分钟。
javascript// 创建一个Ajax对象function createAjax() { var xhr; if (window.XMLHttpRequest) { xhr=new XMLHttpRequest(); } else { xhr=new ActiveXObject(Microsoft.XMLHTTP); } return xhr;}
// 连接服务器function connectServer(url, method, data, callback) { var xhr=createAjax(); xhr.onreadystatechange=function() { if (xhr.readyState==4 && xhr.status==200) { callback(xhr.responseText); } }; xhr.open(method, url, true); xhr.setRequestHeader(Content-Type, application/x-www-form-urlencoded); xhr.send(data);}
// 使用示例connectServer(http://example.com/api/data, POST, key=value, function(response) { console.log(response);});
gistfile1.txtajax的简易编写大致分为四个部分 创建一个Ajax对象,连接服务器,发送请求,接收返回值 在创建对象的时候有一个兼容的问题,IE6不兼容XMLHttpRequest(),因此用if语句进行判断 if(window.XMLHttpRequest) { var oAjax=new XMLHttpRequest(); } else { var oAjax=new ActiveXObject("Microsoft.XMLHTTP"); } 第二步连接服务器 用open方法,open(方法(get/post),文件名,异步传输),在这里可以有一,个清除缓存:缓存是通过url来的,只要让url不停地改变就可以清除缓存,把路径改为 "url?t="+new Date().getTime() 第三部发送请求,直接send() 第四部接收需要判断, readystate属性:请求状态: 0,未调用open() 1,载入send() 2,完成载入send() 3,解析 4,完成 status:完成状态 200-成功,其他失败

