【ajax基础篇】——同步与异步
2016-07-14 09:08
302 查看
AJAX是异步的javascript xml,特征就是允许浏览器与服务器通信而无须刷新当前页面。
一:同步事件
二 :异步事件
一:同步事件
//跨浏览器添加事件 function addEvent(obj, type, fn) { if (obj.addEventListener) { obj.addEventListener(type, fn); } else { obj.attchEvent("on" + type, fn); } }; //同步方式 addEvent(document, "click", function () { var xhr = new XMLHttpRequest();//创建xhr xhr.open('get', 'test.xml? rand=' + Math.random, false); //准备发送请求,以get方式请求,url是test.xml,同步 xhr.send(null); //发送请求,get不需要数据提交,则填写为null //alert(xhr.responseText); //打印出服务器端打印回来的数据 // alert(xhr.status); //获取当前数据的是否成功,成功返回的是200 //alert(xhr.statusText);//获取成功或失败后返回的文本,成功返回OK if (xhr.status == 200) { alert(xhr.responseText); } else { alert('获取数据错误!错误代码:' + xhr.status + '错误信息:' + xhr.statusText); } });
二 :异步事件
//使用异步方式 addEvent(document, "click", function () { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { //只有当页面完成及接受全部的相应后,才真正的使用。分为了xhr.readystate==1,启动;2,发送,3,接受,4,完成。 if (xhr.status == 200) { alert(xhr.responseText); } else { alert('获取数据错误!错误信息:' + xhr.status + '错误信息:' + xhr.statusText); } }; } xhr.open('get', 'test.xml? rand=' + Math.random, true); xhr.abort(); //取消异步的函数。 xhr.send(null); })
相关文章推荐
- C++Primer(5th)第六章page190代码详解
- vim ack
- SEO的心灵窗户:软文技巧
- Asp.Net微信登录-电脑版扫描二维码登录
- 利用thrift实现一个非阻塞带有回调机制的客户端
- [Array] Best Time to Buy and Sell Stock
- 快速入门android AIDL(开启多进程并进行通信)
- power概念模型中表之间的关系
- 登泰山记
- HDU 5135I - Little Zu Chongzhi's Triangles
- obj-x
- 【安卓面试题】多线程下载怎么实现?断点续传怎么实现?
- [Array] Best Time to Buy and Sell Stock
- WebApp开发之Cordova安装教程
- SpringMVC 参数绑定获取的CST时间(Java.util.Date)类型问题
- linux 远程操作命令 SSH SCP
- C#综合揭秘——细说进程、应用程序域与上下文之间的关系
- 如何书写网络请求框架(先知)
- 地球历史很长,而“人”的历史很短
- Android Wear(手表)开发 - 学习指南