對jquery中的$.ajax二次封裝 從而多次調用 今天一整天都在想這個事情


當然了  我封裝的是$.ajax  可以傳參數  多次調用請求接口  為啥我們這地方不注重前端呢  我都不知道為啥去堅持 不說了  上代碼

js文件

$ajax.js

$(function(){ /**  * ajax封裝  * url 發送請求的地址  * data 發送到服務器的數據,數組存儲,如:{"username": "張三", "password": 123456}  * succCallback 成功回調函數  * errorCallback 失敗回調函數  * type 請求方式("POST" 或 "GET"), 默認已經設置為 "POST"  * dataType 預期服務器返回的數據類型,常用的如:xml、html、json、text  * reference jquery-1.7.1.js  */ //插入loading var html = ""; html += '<div class="js_loading">'; html += '<div class="mask"></div>'; html += '<div class="loading">'; html += '<span><img src="loading.gif"></span>'; html += '</div>'; html += '</div>'; $("body").append(html); function $ajax(url, postData, succCallback, errorCallback, type, dataType){ var type = type || "post"; var dataType = dataType || "json"; $.ajax({ type: type, url: url, data: postData, dataType: dataType, beforeSend: function(){ //開始loading $(".js_loading").show(); }, success: function(res){ if(res.success){ if(succCallback){ succCallback(res); } }else{ if(errorCallback){ errorCallback(res); } } }, complete: function(){ //結束loading //$(".js_loading").remove(); $(".js_loading").hide(); } }); } });

是不是一看就明白了  so easy  不要覺得那些面試官出的題目有多難  只是么有反應過來

 

好了 接下來就是調用了

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>ajax再封裝</title> <style> .js_loading{display:none;} .mask{background:rgba(255, 255, 255, 0);position:fixed;left:0;top:0;width:100%;height:100%;z-index:1;} .loading{position:fixed;left:0;top:0;width:100%;height:100%;z-index:2;display:box;box-pack:center;box-align:center;display:-webkit-box;-webkit-box-pack:center;-webkit-box-align:center;} .loading span{display:block;background:#333;width:40px;height:40px;border-radius:3px;text-align:center;} .loading img{width:26px;margin-top:7px;} </style> <script src="jquery-1.7.1.js"></script> </head> <body> <button type="button" class="btn">獲取</button> <div class="box"></div> <script> $(function(){ $(".btn").click(function(){ var postData = { username: '張三', password: 123456 }; $ajax( 'test.asp', postData, function(res){ //成功 $(".box").html(res.firstName); }, function(res){ //失敗 $(".box").html(res.fail); } ); }); }); </script> </body> </html>

還有就是請求的頁面 test.asp

{
    "success":true,
    "firstName":"獲取成功!!!",
    "lastName":"哈哈...",
    "fail":"獲取失敗!!!"
}

自己試試吧  思路一疏通  寫這類的方法不是問題

 

關機睡覺

---恢復內容結束---

當然


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM