下面小编就为大家带来一篇用原生 JS 对 AJAX 做简单封装的实例代码。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
首先,我们需要 xhr 对象。这对我们来说不难,封装成一个函数。
- 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");
- 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: "post",
- url: "test.jsp",
- data: "name=dipoo&info=good",
- dataType: "json",
- success: function(data) {
- alert(data.name);
- }
- });
以上这篇用原生 JS 对 AJAX 做简单封装的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持 phperz。
来源: http://www.phperz.com/article/17/0305/264304.html