var $ax = function (url, success, error) { this.url = url; this.type = "post"; this.data = {}; this.dataType = "json"; this.async = false; this.success = success; this.error = error; }; $ax.prototype = { start : function () { var me = this; if (this.url.indexOf("?") == -1) { this.url = this.url + "?jstime=" + new Date().getTime(); } else { this.url = this.url + "&jstime=" + new Date().getTime(); } $.ajax({ type: this.type, url: this.url, dataType: this.dataType, async: this.async, data: this.data, beforeSend: function(data) { if(window.ajaxNum){ Feng.loader(); $("#spinners").show() } }, success: function(data) {
//这里对返回的数据进行数据 如果登录失效可以直接跳转登录页面 if(data.respCode=='0007'){ window.location.href='/' return false; } me.success(data); }, error: function(data) { me.error(data); } }); }, set : function (key, value) { if (typeof key == "object") { for (var i in key) { if (typeof i == "function") continue; this.data[i] = key[i]; } } else { this.data[key] = (typeof value == "undefined") ? $("#" + key).val() : value; } return this; }, setData : function(data){ this.data = data; return this; }, setObjData: function (kye,value) { // console.log(kye,value) this[kye] = value; }, clear : function () { this.data = {}; return this; } }; window.$ax = $ax;
一.使用方法
1.首先引入封装好的js
<script src="/js/ajax-object.js"></script>
2.页面中使用
var ajax = new $ax("url", function (res) { //返回成功对数据处理
}, function (error) {
//返回失败对数据处理 }); ajax .set("username",'zhangsan');//设置传参 ajax .type='get';//设置请求类型 ajax .start();