轻量级调试api接口 Jquery.PlayingAPI v 1.0

下载

 

源码

 

  1 /*
  2     jQuery playingapi v1.0 - 2014-4-1 
  3     (c) Kevin 21108589@qq.com
  4     license: http://www.opensource.org/licenses/mit-license.php
  5 */
  6 
  7 (function ($) {
  8     //默认对象为空
  9     var defaults = { 
 10     },
 11     //基本的一些定义
 12     error = 'error',
 13     info = 'info',
 14     success = 'success',
 15     zhError = '错误',
 16     zhErrorCode = '错误代码:',
 17     zhRequired = '必填',
 18     zhNoRequired = '非填',
 19     zhSuccess = '成功:',
 20     zhInfo = '信息:',
 21     zhRequest = '请求',
 22     zhReuqestType = 'HTTP请求方式',
 23     zhRequestUrl = '请求地址',
 24     zhUrlParams = '请求参数',
 25     zhUrlParamsDesc = '参数说明',
 26     zhResult = '请求结果',
 27     prefix = 'papi',
 28     playingapifield = 'playingapifield',
 29     form = 'form',
 30     iframe = 'iframe',
 31     data,
 32     requiredField,
 33     isIe = !$.support.leadingWhitespace, // IE7 & IE8
 34     lable = 'lable',
 35     input = 'input',
 36     div = 'div',
 37     span = 'span',
 38     textarea = 'textarea',
 39     descLength = 38,
 40     
 41     //playingapi元素对象 基本的元素均在此定义
 42     playingapielement = {
 43         requestType: {
 44             name: zhReuqestType,
 45             $self: function () {
 46                 var html = $tag(input).addClass("input-xlarge").val("GET").attr("disabled", "").attr("type","text");
 47                 return html;
 48             }
 49         },
 50         requestUrl: {
 51             name: zhRequestUrl,
 52             $self: function () {
 53                 var html = $tag(textarea).attr("rows", "2").attr("disabled", "");
 54                 return html;
 55             }
 56         },
 57         urlParams: {
 58             name: zhUrlParams,
 59             $self: function () {
 60                 var html = $tag(textarea).attr("rows", "2").attr("disabled", "");
 61                 return html;
 62             }
 63         },
 64         urlParamsDesc: {
 65             name: zhUrlParamsDesc,
 66             $self: function () {
 67                 var span1 = $tag(span).addClass("help-inline");
 68                 return span1.append($tag(span).addClass("label label-warning"));
 69             }
 70         },
 71         requestBtn: {
 72             $self: function () {
 73                 var html = $tag(input).attr("type", "submit").addClass("btn btn-primary").val(zhRequest);
 74                 return html;
 75             }
 76         },
 77         result: {
 78             name: zhResult,
 79             $self: function () {
 80                 var html = $tag(div);
 81                 return html;
 82             }
 83         }
 84     };
 85     //构造函数
 86     var playingapi = function (element, options) {
 87         this.init(element, options);
 88     };
 89     /**
 90     *
 91     *playingapi的配置参数
 92     *playingapi的元素
 93     *
 94     **/
 95     playingapi.prototype = {
 96         //初始化
 97         init: function (element, options) {
 98             //合并参数
 99             this.options = $.extend({}, defaults, options);
100             //将当前调用的元素定义到this.$element
101             this.$element = $(element);
102             this.appendHtml();
103             this.bindEvent();
104         },
105         //显示api的内容
106         show: function (index) {
107             this.clear();
108             var thisoption = this.options.list[index];
109             this.$requestType.val(thisoption.requestType.toUpperCase()=="GET"?"GET" :"POST");
110             this.$requestUrl.val(thisoption.url).attr("title", thisoption.url);
111             this.$urlParams.val(thisoption.urlParams).attr("title", thisoption.urlParams);
112             this.$urlParamsDesc.text(thisoption.urlDesc);
113             var parent = this.$urlParamsDesc.parent().parent().parent();
114            
115             if (thisoption.urlDesc != "") {
116                 parent.show();
117             } else {
118                 parent.hide();
119             }
120 
121             if (thisoption.name != undefined) {
122                 if (thisoption.name != "") {
123                     var html = "";
124                     var name, value, desc, json;
125                     requiredField = thisoption.requiredName;
126                     for (var i = 0; i < thisoption.name.split(',').length; i++) {
127                         name = thisoption.name.split(',');
128                         value = thisoption.value == undefined ? "" : thisoption.value.split(',');
129                         desc = thisoption.desc == undefined ? "" : thisoption.desc.split(',');
130                         json = {
131                             name: name[i],
132                             value: value[i] == undefined ? "" : value[i],
133                             desc: desc[i] == undefined ? "" : desc[i]
134                         };
135                         html += getHelpGroupHtml(json);
136                     }
137                     var uploadfilename;
138                     if (thisoption.uploadfile != undefined) {
139                         uploadfilename = thisoption.uploadfile.name.split(',');
140                         value = thisoption.uploadfile.value.split(',');
141                         for (var j = 0; j < uploadfilename.length; j++) {
142                             json = {
143                                 name: uploadfilename[j],
144                                 value: value[j]
145                             };
146                             html += getUploadFileHtml(json);
147                         }
148                     }
149                     //添加缓存数据的dom
150                     this.$form.find(".control-group").eq(4).before(html);
151                     //填充action当前form
152                     this.$form.attr("action", this.$requestUrl.val());
153                 }
154             }
155            
156         },
157         //添加playingapi需要的dom
158         appendHtml: function () {
159             var tform = $tag(form).attr("method","post").attr("enctype", "multipart/form-data").addClass("bs-docs-example form-horizontal");
160             var trequestType = getGroupHtml(playingapielement.requestType);
161             var trequestUrl = getGroupHtml(playingapielement.requestUrl);
162             var turlParams = getGroupHtml(playingapielement.urlParams);
163             var turlParamsDesc = getGroupHtml(playingapielement.urlParamsDesc);
164           
165             turlParamsDesc.css("display", "none");
166             var trequestBtn = getGroupHtml(playingapielement.requestBtn);
167             var tiframe = $tag(iframe,iframe).css("display", "none");
168             var tresult = getGroupHtml(playingapielement.result);
169             this.$element.append(tform.append(trequestType, trequestUrl, turlParams, turlParamsDesc, trequestBtn,tresult, tiframe));
170             
171             var dataname = "data";
172             if (this.$data == undefined) {
173                 var tdata = $tag(input, dataname).css("display", "none").attr("name", prefix + dataname);
174                 this.$data = tdata;
175                 this.$element.append(tdata);
176             }
177 
178             //定义当前变量
179             this.$form = tform;
180             this.$iframe = tiframe;
181             this.$requestType = trequestType.find(".controls>input");
182             this.$requestUrl = trequestUrl.find(".controls>textarea");
183             this.$urlParams = turlParams.find(".controls>textarea");
184             this.$urlParamsDesc = turlParamsDesc.find(".controls>span>span");
185             this.$requestBtn = trequestBtn.find(".controls>input");
186             this.$result = tresult.find(".controls>div");
187         },
188         //绑定事件
189         bindEvent: function () {
190             var thisobj = this;
191             var fnajaxForm = $.fn.ajaxSubmit;
192             this.$requestBtn.bind("click", ($.proxy(function () {
193                 if (thisobj.$urlParams.val() != "") {
194                     thisobj.setDataJson();
195                     thisobj.$form.append($(thisobj.$data));
196                     //如果有用到jquery.form.js就使用该方法
197                     if ($.isFunction(fnajaxForm)) {
198                         thisobj.$form.ajaxForm({
199                             //target: $(thisobj.$iframe),
200                             error: function (XMLHttpRequest) {
201                                 thisobj.showResult({ type: error, info: XMLHttpRequest.status });
202                             },
203                             success: function (data) {
204                                 thisobj.showResult({ type: success, info: data });
205                             }
206                         });
207                     } else {
208                         //否则使用jquery.$.ajax
209                         $.ajax({
210                             type: this.$requestType.val(),
211                             data: this.$data.attr("id")+"="+this.$data.val(),
212                             url: this.$requestUrl.val(),
213                             error: function(XMLHttpRequest) {
214                                 thisobj.showResult({ type: error, info: XMLHttpRequest.status });
215                             },
216                             success: function(data) {
217                                 thisobj.showResult({ type: success, info: data });
218                             }
219                         });
220                         //阻止表单提交
221                         return false;
222                     }
223                 } else {
224                     //阻止表单提交
225                     return false;
226                 }
227             },this)));
228         },
229         //移除临时块
230         clear: function() {
231             $(".tempclass").remove();
232         },
233         //将form的数据转换的json保存到data元素
234         setDataJson: function() {
235             var json = "{";
236             var formobj = this.$form.find("." + playingapifield);
237             var flen = formobj.length;
238           
239             formobj.each(function (i) {
240                 var obj = $(this);
241                 json += "'" + obj.attr("name") + "'" + ":" + "'" + obj.val() + "'";
242                 if (i != flen - 1) {
243                     json += ",";
244                 }
245                 i++;
246             });
247       
248             json += "}";
249             this.$data.val(json);
250         },
251         //显示返回内容
252         showResult: function (obj) {
253             var html = "<div class=\"alert alert-arg0\" style='width:363px'>arg1</div>";
254             var regtype = new RegExp("arg0", "g");
255             var reginfo = new RegExp("arg1", "g");
256             if (obj != undefined) {
257                 switch (obj.type) {
258                 case error:
259                     html = html.replace(regtype, error).replace(reginfo, zhErrorCode + obj.info);
260                     break;
261                 case success:
262                     html = html.replace(regtype, success).replace(reginfo, zhSuccess + obj.info);
263                     break;
264                 case info:
265                     html = html.replace(regtype, info).replace(reginfo, zhInfo + obj.info);
266                     break;
267                 default:
268                 }
269                 this.$result.html(html);
270 //                var offset = this.$result.offset().top;
271 //                $(window).scrollTop(offset);
272             }
273         }
274     };
275     
276     /**
277    *
278    *通用函数
279    *
280    **/
281 
282     //获取css临时的帮助div块
283     function getHelpGroupHtml(obj) {
284         var html = "<div class='control-group tempclass'>";
285         html += "<label class='control-label'>" + obj.name + "</label><div class='controls'><input type='text' name='" + obj.name + "' value='" + obj.value + "'  class='" + playingapifield + "'>";
286         eval("var re = /" + obj.name + "/ig;");
287         html += "<span class='help-inline'>";
288         
289         //判断该字段是否必填的,填充"必填",或 "非填"
290         if (re.test(requiredField)) {
291             html += "&nbsp;<span class='label label-important'>" + zhRequired + "</span>";
292         } else {
293             html += "&nbsp;<span class='label label-inverse'>" + zhNoRequired + "</span>";
294         }
295         //过长tip显示
296         if (obj.desc.length >= descLength) {
297             html += "&nbsp;<span class='label label-info tip' title='" + obj.desc + "'>" + obj.desc.substr(0, descLength) + "..." + "</span>";
298         } else {
299             html += "&nbsp;<span class='label label-info'>" + obj.desc + "</span>";
300         }
301         html += "</span></div></div>";
302         return html;
303     }
304 
305     //获取css临时的文件上传div块
306     function getUploadFileHtml(obj) {
307         var html = '<div class="control-group tempclass">' +
308         '<label class="control-label">arg0</label>' +
309         '<div class="controls">' +
310         '<input type="file" id="arg1" class="input-xlarge ' + playingapifield + '" name="arg1"  value="file"/>' +
311         '</div></div>';
312         var reg = new RegExp("arg0", "g");
313         html = html.replace(reg, obj.name);
314         reg = new RegExp("arg1", "g");
315         html = html.replace(reg, obj.value);
316         return html;
317     }
318     
319     //获取css主要的div块
320     function getGroupHtml(element) {
321         var $div1 = $tag(div).addClass("control-group");
322         var $lable = $tag(lable).addClass("control-label").text(element.name);
323         var $div2 = $tag(div).addClass("controls");
324         var $elementHtml = element.$self();
325         var html = $div1.append($lable);
326         html = html.append($div2.append($elementHtml));
327         return html;
328     }
329 
330     //创建jquery对象
331     function $tag(tag, id, css) {
332         var element = document.createElement(tag);
333         if (id) {
334             element.id = prefix + id;
335         }
336         if (css) {
337             element.style.cssText = css;
338         }
339         return $(element);
340     };
341 
342     $.fn.playingapi = function (option) {
343         var args = arguments;
344         $(this).each(function() {
345             data = $(this).data("playingapi");
346             options = (typeof option !== 'object') ? null : option;
347             if (!data) {
348                 //new 一个新的对象 并缓存数据到playingapi
349                 data = new playingapi(this, options);
350                 $(this).data("playingapi",data);
351             }
352             if (typeof option === 'string') {
353                 //调用option,且参数长度最多为1
354                 data[option].apply(data, Array.prototype.slice.call(args, 1));
355             }
356         });
357     }; 
358    
359 }(window.jQuery));

 

posted @ 2014-04-01 19:42  chenchangwen  阅读(713)  评论(0编辑  收藏  举报