原生ajax学习
文档是看的官网文档(有借鉴但是网站忘记了) 后面代码是自己写的
ajax优缺点
优点
- 异步传输
AJAX使用异步方式与服务器通信,不需要打断用户的操作,具有更加迅速的响应能力。优化了Browser和Server之间的沟通,减少不必要的数据传输、时间及降低网络上数据流量 - 无刷新更新数据
AJAX最大优点就是能在不刷新整个页面的前提下与服务器通信维护数据。这使得Web应用程序更为迅捷地响应用户交互,并避免了在网络上发送那些没有改变的信息,减少用户等待时间,带来非常好的用户体验。 - 前后端负载平衡
AJAX可以把以前一些服务器负担的工作转嫁到客户端,利用客户端闲置的能力来处理,减轻服务器和带宽的负担,节约空间和宽带租用成本。并且减轻服务器的负担,AJAX的原则是“按需取数据”,可以最大程度的减少冗余请求和响应对服务器造成的负担,提升站点性能。 - 界面与应用分离
Ajax使WEB中的界面与应用分离(也可以说是数据与呈现分离),有利于分工合作、减少非技术人员对页面的修改造成的WEB应用程序错误、提高效率、也更加适用于现在的发布系统。 - 基本标准被广泛支持
AJAX基于标准化的并被广泛支持的技术==,不需要下载浏览器插件或者小程序==,但需要客户允许JavaScript在浏览器上执行。随着Ajax的成熟,一些简化Ajax使用方法的程序库也相继问世。同样,也出现了另一种辅助程序设计的技术,为那些不支持JavaScript的用户提供替代功能。
缺点
- AJAX干掉了Back和History功能,即对浏览器机制的破坏
- AJAX的安全问题。
- 对搜索引擎支持较弱。
- 破坏程序的异常处理机制。
- AJAX不能很好支持移动设备。
- 客户端过肥,太多客户端代码造成开发上的成本。
编写复杂、容易出错 ;冗余代码比较多(层层包含js文件是AJAX的通病,再加上以往的很多服务端代码现在放到了客户端);破坏了Web的原有标准。
原生ajax方法
1、创建XMLHttpRequest()对象
XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
// 大部分浏览器支持XMLHttpRequestvar req = new XMLHttpRequest();// 兼容IE6写法var xmlHttp = new ActiveXObject('Microsoft.XMLHttp')// 完整写法if(window.XMLHttpRequset){// code for IE7+, Firefox, Chrome, Opera, Safarivar xmlHttp = new XMLHttpRequest();}else{// code for IE5, IE6var xmlHttp = new ActiveXObject('Microsoft.XMLHttp');}
2、向服务器发送请求
使用 XMLHttpRequest 对象的 open() 和 send() 方法:
规定请求连接和类型
open(method, url, async)
向服务器发送请求
send(string) string仅用于post请求
如果需要想接口传数据get方法直接在链接后面拼数据字符串;如果post传数据需要使用 setRequestHeader() 来添加 HTTP 头
// getxmlHttp.open("get", "xxx.xxx.js?aaa=111&b=222", true);//postxmlHttp.open("POST","ajax_test.asp",true);xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlHttp.send("fname=Bill&lname=Gates");
注释:当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可
xmlhttp.open("GET","test1.txt",false);xmlhttp.send();// TODOdocument.getElementById("myDiv").innerHTML=xmlhttp.responseText;
3、服务器响应
responseText 获取字符串类型的相响应数据
responseXML 获取XML类型的响应数据
xmlHttp.responseTextxmlHttp.responseXML
4、响应事件 xmlHttp.onreadystatechange
当readyState改变是会触发onreadystatechange事件
下面是 XMLHttpRequest 对象的三个重要的属性:
| 属性 | 描述 |
|---|---|
| onreadystatechange | 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。 |
| readyState | 存有 XMLHttpRequest 的状态。从 0 到 4发生变化。 |
| status | 200: “OK” 404: 未找到页面 |
readyState各种状态
- 0: 请求未初始化
- 1: 服务器连接已建立
- 2: 请求已接收
- 3: 请求处理中
- 4: 请求已完成,且响应已就绪
当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
xmlHttp.onreadystatechange = function() {if(xmlHttp.state == '200' && xmlHttp.readyState == '4'){// do something}}
Demo
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>原生ajax请求</title><script>var getData = function() {var xmlhttp;if(window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}else{xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');}xmlhttp.onreadystatechange = function () {if(xmlhttp.readyState == 4 && xmlhttp.status == 200){console.log(xmlhttp.responseText);document.getElementById('text').innerHTML = xmlhttp.responseText;}}xmlhttp.open('get', 'http://xxx.xxx.com/mobile/index.php?act=area&op=area_list_arr2', true);xmlhttp.send();}</script></head><body><button onclick="getData()">获取后台数据</button><div id="text"></div></body></html>
ajax 封装 只有基本使用
/*** @author: zhaoyangyue* @param param=defaultParam 和defaultParam的格式一樣就可以* param传对象*//function ajax(param) {var xmlhttp;var defaultParam = {type: 'get',url: '',async: true,dataType: '',success: function () {return;},error: function () {alert('网络错误');}}for(var i in defaultParam){if(!param[i]){param[i] = defaultParam[i];}}if(window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}else{xmlhttp = new ActiveXObject('Microsoft XMLHTTP');}if(param.type.toLowerCase() == 'post'){// post方法传值需要设置请求头 get不用Content-Type:application/x-www-form-urlencodedxmlhttp.open(param.type, param.url, param.async);xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');xmlhttp.send(param.data);}else{if(param.url.indexOf('?') > -1){xmlhttp.open(param.type, param.url + '&' + param.data , param.async);}else{xmlhttp.open(param.type, param.url + '?' + param.data , param.async);}xmlhttp.send();}if(param.async){xmlhttp.onreadystatechange = function () {// ajax运行状态为4 已完成请求 并且请求成功if(xmlhttp.readyState == 4 && xmlhttp.status == 200){// TODOif(param.dataType == 'json'){param.success(JSON.parse(xmlhttp.responseText));}else{param.success(xmlhttp.responseText)}}else if(xmlhttp.readyState == 4 && xmlhttp.status != 200){if(param.dataType == 'json'){param.error(JSON.parse(xmlhttp.responseText));}else{param.error(xmlhttp.responseText)}}}}else{param.success(xmlhttp.responseText);}}
完整案例
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>原生ajax请求</title></head><body><button onclick="ajax(object)">get获取后台数据</button><button onclick="ajax(post)">POST</button><div id="text"></div></body></html><script>//AJAX封装var object = {type: 'get',url: 'http://xxx.xxx.com/mobile/index.php',async: true,data: 'act=area&op=area_list_arr2',// dataType: 'json',success: function (res) {// callbackconsole.log(res);document.getElementById('text').innerHTML = res;},error: function (err) {// callbackconsole.log(err)}}var post = {type: 'post',url: 'http://xxx.xxx.com/mobile/index.php?act=member_order&op=get_current_deliver',// async: true,data: 'key=xxx&order_id=292',dataType: 'json',success: function (res) {console.log(res);},error: function (err) {alert('false');console.log(err)}}/*** @author: zyy_cherish@163.com* @param param=defaultParam 和defaultParam的格式一樣就可以* param传对象*//function ajax(param) {var xmlhttp;var defaultParam = {type: 'get',url: '',async: true,dataType: '',success: function () {return;},error: function () {alert('网络错误');}}for(var i in defaultParam){if(!param[i]){param[i] = defaultParam[i];}}xmlhttp = window.XMLHttpRequest ? xmlhttp = new XMLHttpRequest() || new ActiveXObject('Microsoft XMLHTTP');if(param.type.toLowerCase() == 'post'){// post方法传值需要设置请求头 get不用Content-Type:application/x-www-form-urlencodedxmlhttp.open(param.type, param.url, param.async);xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');xmlhttp.send(param.data);}else{if(param.url.indexOf('?') > -1){xmlhttp.open(param.type, param.url + '&' + param.data , param.async);}else{xmlhttp.open(param.type, param.url + '?' + param.data , param.async);}xmlhttp.send();}if(param.async){xmlhttp.onreadystatechange = function () {// ajax运行状态为4 已完成请求 并且请求成功if(xmlhttp.readyState == 4 && xmlhttp.status == 200){// TODOif(param.dataType == 'json'){param.success(JSON.parse(xmlhttp.responseText));}else{param.success(xmlhttp.responseText)}}else if(xmlhttp.readyState == 4 && xmlhttp.status != 200){if(param.dataType == 'json'){param.error(JSON.parse(xmlhttp.responseText));}else{param.error(xmlhttp.responseText)}}}}else{param.success(xmlhttp.responseText);}}</script>
