原生js实现ajax
来源:互联网 发布:淘宝好评怎么改成差评 编辑:程序博客网 时间:2024/04/28 04:44
原生javascript实现ajax
实现如下,类似jquery的ajax,可以对返回值操作:
/** * 实现ajax */var createAjax = function() { var xhr = null; try { //IE系列浏览器 xhr = new ActiveXObject("microsoft.xmlhttp"); } catch (e1) { try { //非IE浏览器 xhr = new XMLHttpRequest(); } catch (e2) { window.alert("您的浏览器不支持ajax,请更换!"); } } return xhr;};var ajax = function(conf) { // 初始化 //type参数,可选 var type = conf.type; //url参数,必填 var url = conf.url; //data参数可选,只有在post请求时需要 var data = conf.data; //datatype参数可选 var dataType = conf.dataType; //回调函数可选 var success = conf.success; if (type == null){ //type参数可选,默认为get type = "get"; } if (dataType == null){ //dataType参数可选,默认为text dataType = "text"; } // 创建ajax引擎对象 var xhr = createAjax(); // 打开 xhr.open(type, url, true); // 发送 if (type == "GET" || type == "get") { xhr.send(null); } else if (type == "POST" || type == "post") { xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8"); xhr.send(data); } xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if(dataType == "text"||dataType=="TEXT") { if (success != null){ //普通文本 success(xhr.responseText); } }else if(dataType=="xml"||dataType=="XML") { if (success != null){ //接收xml文档 success(xhr.responseXML); } }else if(dataType=="json"||dataType=="JSON") { if (success != null){ //将json字符串转换为js对象 success(eval("("+xhr.responseText+")")); } } } };};
使用方法:
ajax({ type : "get", url : "test.json", dataType : "json", success : function(data) { } });
0 0
- 原生js实现Ajax
- 原生js实现ajax
- 原生JS实现Ajax
- 原生js实现ajax
- 原生js实现Ajax
- 原生js实现Ajax
- 原生js实现ajax
- 原生JS实现ajax请求
- 原生js实现ajax方法
- JS实现原生Ajax原理图
- 原生js实现ajax方法
- Ajax(原生js实现、jQuery实现、跨域)
- 用原生js实现jquery ajax
- 【Javascript】原生js实现ajax功能
- 原生js使用xmlhttpRequest实现ajax请求
- 原生js与jquery实现ajax
- 原生JS实现AJAX的思路
- 使用原生js实现ajax请求
- 字符替换+时间转换
- Uplodify相关参数说明
- 各种cpu指令集对应的iPhone设备总结
- command not found mysql
- 页面内容是js但是文件名是zhtml,高亮显示会有问题,解决方法
- 原生js实现ajax
- CGContextMoveToPoint与CGContextAddLineToPoint详解
- SDUT 3375 数据结构实验之查找三:树的种类统计
- UCOSIII相关API函数的使用
- Solr之——SolrCloud5.2.1+tomcat7+zookeeper3.4.6环境搭建
- 熄灯问题
- SpringMVC介绍之约定优于配置
- Tomcat调优
- android Spinner控件详解