当然了 我封装的是$.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":"获取失败!!!"
}
自己试试吧 思路一疏通 写这类的方法不是问题
关机睡觉
---恢复内容结束---
当然