对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":"获取失败!!!"
}

自己试试吧  思路一疏通  写这类的方法不是问题

 

关机睡觉

---恢复内容结束---

当然

转载于:https://www.cnblogs.com/guohongjun/p/7071971.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值