jquery.ajax函式封裝--通用
阿新 • • 發佈:2018-12-25
轉載:寫重複的方法 和程式碼,冗餘太大, 也浪費時間,找了一個通用的ajax,只需要傳引數就行
/***************************************************************** jQuery Ajax封裝通用類 (linjq) *****************************************************************/ $(function(){ /** * ajax封裝 * url 傳送請求的地址 * data 傳送到伺服器的資料,陣列儲存,如:{"date": new Date().getTime(), "state": 1} * async 預設值: true。預設設定下,所有請求均為非同步請求。如果需要傳送同步請求,請將此選項設定為 false。 * 注意,同步請求將鎖住瀏覽器,使用者其它操作必須等待請求完成才可以執行。 * type 請求方式("POST" 或 "GET"), 預設為 "GET" * dataType 預期伺服器返回的資料型別,常用的如:xml、html、json、text * successfn 成功回撥函式 * errorfn 失敗回撥函式 */ jQuery.ax=function(url, data, async, type, dataType, successfn, errorfn) { async = (async==null || async=="" || typeof(async)=="undefined")? "true" : async; type = (type==null || type=="" || typeof(type)=="undefined")? "post" : type; dataType = (dataType==null || dataType=="" || typeof(dataType)=="undefined")? "json" : dataType; data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: type, async: async, data: data, url: url, dataType: dataType, success: function(d){ successfn(d); }, error: function(e){ errorfn(e); } }); }; /** * ajax封裝 * url 傳送請求的地址 * data 傳送到伺服器的資料,陣列儲存,如:{"date": new Date().getTime(), "state": 1} * successfn 成功回撥函式 */ jQuery.axpost=function(url, data, successfn) { data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: "post", data: data, url: url, dataType: "json", success: function(d){ successfn(d); } }); }; /** * ajax封裝 * url 傳送請求的地址 * data 傳送到伺服器的資料,陣列儲存,如:{"date": new Date().getTime(), "state": 1} * dataType 預期伺服器返回的資料型別,常用的如:xml、html、json、text * successfn 成功回撥函式 * errorfn 失敗回撥函式 */ jQuery.axspost=function(url, data, successfn, errorfn) { data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: "post", data: data, url: url, dataType: "json", success: function(d){ successfn(d); }, error: function(e){ errorfn(e); } }); }; }); --------------------- 作者:郭小北V5 來源:CSDN 原文:https://blog.csdn.net/xllily_11/article/details/51567186 版權宣告:本文為博主原創文章,轉載請附上博文連結!