diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..25c8fdb --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +package-lock.json \ No newline at end of file diff --git a/README.md b/README.md index 0565710..5e25f3c 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ ajax({ url:"", //添加自己的接口链接 timeOut:5000, before:function(){ - console.log("before"); + console.log("before"); }, success:function(str){ console.log(str); @@ -30,6 +30,7 @@ ajax({ | dataType | "" | 请求的类型 | jsonp | | async | true | 是否异步 | blooean | | timeOut | undefined | 超时时间 | number | +| callbackName | "" | JSONP的callback函数名称 | string | | before | function(){} | 发送之前执行的函数 | function | | error | function(){} | 请求报错执行的函数 | function | | success | function(){} | 请求成功的回调函数 | function | diff --git a/ajax.js b/ajax.js index 64d69cb..2f000c5 100644 --- a/ajax.js +++ b/ajax.js @@ -1,4 +1,5 @@ (function(window,undefined) { + // 定义Ajax类 function ajax(options) { //编码数据 @@ -25,12 +26,16 @@ } } else if (Object.prototype.toString.call(data) == '[object Object]') { for (var key in data) { - value = data[key]; - arr = arr.concat(encodeData(key, value, parentName)); + if (data.hasOwnProperty(key)) { // 排除原型中的属性 + if(typeof data[key] !== 'function') { // 排除函数类型的属性 + value = data[key]; + arr = arr.concat(encodeData(key, value, parentName)); + } + } } } return arr; - }; + } //设置字符串的遍码,字符串的格式为:a=1&b=2; function setStrData(data) { var arr = data.split("&"); @@ -48,7 +53,7 @@ } else if (typeof data === "object") { data = setObjData(data); } - data = data.join("&").replace("/%20/g", "+"); + data = data.join("&").replace(/%20/g, "+"); //若是使用get方法或JSONP,则手动添加到URL中 if (type === "get" || dataType === "jsonp") { url += url.indexOf("?") > -1 ? (url.indexOf("=") > -1 ? "&" + data : data) : "?" + data; @@ -59,13 +64,13 @@ function createJsonp() { var script = document.createElement("script"), timeName = new Date().getTime() + Math.round(Math.random() * 1000), - callback = "JSONP_" + timeName; + callback = options.callbackName ? options.callbackName : ("JSONP_" + timeName); // 如果没有提供JSONP的callback名称,则使用随机名称 window[callback] = function(data) { clearTimeout(timeout_flag); document.body.removeChild(script); success(data); - } + }; script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + "callback=" + callback; script.type = "text/javascript"; document.body.appendChild(script); @@ -129,10 +134,19 @@ clearTimeout(timeout_flag); } if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { - - success(xhr.responseText); + // 判断响应数据的MIME类型,采用对应的解码方式 + var type = xhr.getResponseHeader("Content-Type"); + if (type.indexOf("xml") != -1 && xhr.responseXML) { + success(xhr.responseXML); + } else if (type.match(/^application\/json/)) { + success(JSON.parse(xhr.responseText)); + } else { + success(xhr.responseText); + } } else { - error(xhr.status, xhr.statusText); + // 将原始数据也传入 + // 最后一个参数只针对JSON数据类型有效 + error(xhr.status, xhr.statusText, JSON.parse(xhr.responseText)); } } }; @@ -148,7 +162,8 @@ contentType = options.contentType || "", //请求头 dataType = options.dataType || "", //请求的类型 async = options.async === undefined ? true : options.async, //是否异步,默认为true. - timeOut = options.timeOut, //超时时间。 + timeOut = options.timeOut, //超时时间。 + callbackName = options.callbackName || "", // 自定义JSONP的callback名称 before = options.before || function() {}, //发送之前执行的函数 error = options.error || function() {}, //错误执行的函数 success = options.success || function() {}; //请求成功的回调函数 diff --git a/ajax.min.js b/ajax.min.js index 6019063..a39321c 100644 --- a/ajax.min.js +++ b/ajax.min.js @@ -1 +1 @@ -!function(a,b){function c(c){function d(){function a(c,d){function e(c,d,e){var f=[];return c=e===b?c:e+"["+c+"]","object"==typeof d&&null!==d?f=f.concat(a(d,c)):(c=encodeURIComponent(c),d=encodeURIComponent(d),f.push(c+"="+d)),f}var g,f=[];if("[object Array]"==Object.prototype.toString.call(c))for(var h=0,i=c.length;i>h;h++)g=c[h],f=f.concat(e("object"==typeof g?h:"",g,d));else if("[object Object]"==Object.prototype.toString.call(c))for(var j in c)g=c[j],f=f.concat(e(j,g,d));return f}function c(a){for(var b=a.split("&"),c=0,d=b.length;d>c;c++)name=encodeURIComponent(b[c].split("=")[0]),value=encodeURIComponent(b[c].split("=")[1]),b[c]=name+"="+value;return b}j&&("string"==typeof j?j=c(j):"object"==typeof j&&(j=a(j)),j=j.join("&").replace("/%20/g","+"),("get"===i||"jsonp"===l)&&(h+=h.indexOf("?")>-1?h.indexOf("=")>-1?"&"+j:j:"?"+j))}function e(){var b=document.createElement("script"),c=(new Date).getTime()+Math.round(1e3*Math.random()),d="JSONP_"+c;a[d]=function(a){clearTimeout(s),document.body.removeChild(b),q(a)},b.src=h+(h.indexOf("?")>-1?"&":"?")+"callback="+d,b.type="text/javascript",document.body.appendChild(b),f(d,b)}function f(c,d){n!==b&&(s=setTimeout(function(){"jsonp"===l?(delete a[c],document.body.removeChild(d)):(r=!0,t&&t.abort()),console.log("timeout")},n))}function g(){function c(){if(a.XMLHttpRequest)return new XMLHttpRequest;for(var b=["Microsoft","msxm3","msxml2","msxml1"],c=0;c=200&&t.status<300||304==t.status?q(t.responseText):p(t.status,t.statusText)}},t.send("get"===i?null:j),f()}var h=c.url||"",i=(c.type||"get").toLowerCase(),j=c.data||null,k=c.contentType||"",l=c.dataType||"",m=c.async===b?!0:c.async,n=c.timeOut,o=c.before||function(){},p=c.error||function(){},q=c.success||function(){},r=!1,s=null,t=null;d(),o(),"jsonp"===l?e():g()}a.ajax=c}(window); \ No newline at end of file +!function(T,v){T.ajax=function e(o){function a(e,t){u!==v&&(d=setTimeout(function(){"jsonp"===s?(delete T[e],document.body.removeChild(t)):(f=!0,m&&m.abort()),console.log("timeout")},u))}var c=o.url||"",t=(o.type||"get").toLowerCase(),n=o.data||null,r=o.contentType||"",s=o.dataType||"",i=o.async===v||o.async,u=o.timeOut,e=(o.callbackName,o.before||function(){}),l=o.error||function(){},p=o.success||function(){},f=!1,d=null,m=null;!function y(){n&&("string"==typeof n?n=function e(e){for(var t=e.split("&"),n=0,o=t.length;n { + gulp.src(src) + .pipe(minify({ + ie8: true + })) + .pipe(rename({ + basename: 'ajax', + suffix: '.min' + })) + .pipe(gulp.dest(dist)) +}) \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..658b301 --- /dev/null +++ b/package.json @@ -0,0 +1,27 @@ +{ + "name": "ajax", + "version": "1.0.0", + "description": "a simple ajax library", + "main": "ajax.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/gaoshu883/ajax.git" + }, + "keywords": [ + "ajax" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/gaoshu883/ajax/issues" + }, + "homepage": "https://github.com/gaoshu883/ajax#readme", + "devDependencies": { + "gulp": "^3.9.1", + "gulp-rename": "^1.3.0", + "gulp-uglify": "^3.0.0" + } +}