一套通用Ajax框架的源代码

开发 前端
本文提供了一套一套通用Ajax框架的源代码。这段JavaScript代码中提供了两个Demo函数,分别是使用同步、异步对同一个URL进行多次请求。

本次的Ajax框架代码中没有关于实现浏览器前进、后退按钮的处理,如果各位需要,可以从我原来的文章中获取相应的代码。

声明:本文中的所有代码遵守GNU GPLv2的协议,对代码进行开源

发行注记:
2009/06/22
1、取消很多不必要的参数
2、代码风格更加面向对象
3、允许用户对request请求方式进行设置(即用户可以选择同步或异步执行Ajax请求)
4、框架使用闭包封装
5、改进了程序的执行性能

JavaScript代码中提供了两个Demo函数,分别是使用同步、异步对同一个URL进行多次请求。

如果各位对这套框架有什么意见或建议,可以直接联系我,在代码的版权信息内,有本人的电子邮件地址

  1. /*      
  2. * Copyright © 2008 Nervous Studio, All rights reserved.      
  3. *           
  4. * LICENSE      
  5. *           
  6. * This program is free software; you can redistribute it and/or      
  7. * modify it under the terms of the GNU General Public License (GPL)      
  8. * as published by the Free Software Foundation; either version 2      
  9. * of the License, or (at your option) any later version.      
  10. *      
  11. * This program is distributed in the hope that it will be useful,      
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of      
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.        See the      
  14. * GNU General Public License for more details.      
  15. *           
  16. * To read the license please visit http://www.gnu.org/copyleft/gpl.html      
  17. *           
  18. */   
  19.  
  20. /*      
  21. * @author Steven Wee       
  22. *  @E-Mail:wmkm0113@Hotmail.comweimin0528@139.com   
  23. * @version $Revision: 1.1 $ $Date: 2009/06/21 4:40:00 $      
  24. */      
  25.  
  26. //  Get Elements by input elementId   
  27. function $() {   
  28.   if ( arguments.length <= 0 ) {   
  29.     return null;   
  30.   } else {   
  31.     var returnElements = new Array();   
  32.     var argCount = arguments.length;   
  33.     for ( var i = 0 ; i < argCount ; i++ ) {   
  34.       var element = null;   
  35.       var elementId = arguments[i];   
  36.       if ( typeof elementId == 'string' ) {   
  37.         element = document.getElementById(elementId);   
  38.       }   
  39.       if ( element != null ) {   
  40.         returnElements.push(element);   
  41.       }   
  42.     }   
  43.     return returnElements;   
  44.   }   
  45. }   
  46.  
  47. //  Trim the string spaces at begin and end   
  48. function trim(str){   
  49.   return str.replace(/(^\s*)|(\s*$)/g, "");   
  50. }   
  51.  
  52. function AjaxObject() {   
  53.       
  54.   //  Define url address varibale   
  55.   var url = null;   
  56.       
  57.   //  Define formId varibale   
  58.   var formId = null;   
  59.       
  60.   //  Define bindElementId varibale   
  61.   var bindElementId = null;   
  62.       
  63.   //  Define XMLHTTPRequest object varibale   
  64.   var request = getAjaxObject();   
  65.       
  66.   function setURL(urlAddress) {   
  67.     this.url = urlAddress;   
  68.   }   
  69.       
  70.   function getURL() {   
  71.     return this.url;   
  72.   }   
  73.       
  74.   function setFormId(inputFormId) {   
  75.     this.formId = inputFormId;   
  76.   }   
  77.       
  78.   function getFormId() {   
  79.     return this.formId;   
  80.   }   
  81.       
  82.   function setBindElementId(elementId) {   
  83.     this.bindElementId = elementId;   
  84.   }   
  85.       
  86.   function getBindElementId() {   
  87.     return this.bindElementId;   
  88.   }   
  89.       
  90.   /*   
  91.   *  Get XMLHttpRequest object   
  92.   */   
  93.   function getAjaxObject() {   
  94.     var xmlHttpRequest;   
  95.     //  If XMLHttpRequest is a javascript object in the local   
  96.     if(window.XMLHttpRequest){   
  97.       xmlHttpRequest = new XMLHttpRequest();   
  98.     }else if(window.ActiveXObject){  //  Support the ActiveX   
  99.       try{   
  100.         //  Create XMLHttpRequest object by instance an ActiveXObject   
  101.         xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");  //  higher than msxml3   
  102.       }catch(e){   
  103.         try{   
  104.           //  Create XMLHttpRequest object by instance an ActiveXObject   
  105.           xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");  //  lower than msxml3   
  106.         }catch(e){}   
  107.       }   
  108.     }   
  109.     if ( !xmlHttpRequest ) {   
  110.       alert("Create Ajax object failed!");   
  111.     }   
  112.     return xmlHttpRequest;   
  113.   }   
  114.       
  115.   /*   
  116.   *  Send client request by ajax   
  117.   *  Support 'POST' and 'GET' to submit the form   
  118.   *  Support Asynchronous or Synchronous to send the ajax request   
  119.   */   
  120.   function sendRequestByAjax(syncOption, sendOption) {   
  121.     if ( typeof syncOption == "string" && syncOption.toUpperCase() == "POST" ) {   
  122.             request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");   
  123.     }   
  124.     if ( sendOption ) {   
  125.       request.onreadystatechange = processRequest;   
  126.     }   
  127.     request.open(syncOption, this.url, sendOption);   
  128.     var data = null;   
  129.     //  Format form data   
  130.     if ( this.formId && this.formId.length != 0 ) {   
  131.       var formElement = $(this.formId)[0];   
  132.       data = encodeFormData(formElement);   
  133.     }   
  134.     request.send(data);   
  135.   }   
  136.       
  137.   /*   
  138.   *  Ajax callback function when Synchronous   
  139.   */   
  140.   function processRequest() {   
  141.     if( request.readyState == 4 ){   
  142.       //  Receive the request data finished   
  143.       if( request.status == 200 ){   
  144.         //  Received data success   
  145.         if ( request.responseXML.documentElement != null ) {   
  146.           var xmlDoc = request.responseXML.documentElement;   
  147.           var xmlRoot = xmlDoc.getElementsByTagName("dataType");   
  148.           var dataType = xmlRoot[0].childNodes[0].firstChild.nodeValue;   
  149.           var items = xmlDoc.getElementsByTagName('item');   
  150.           switch ( dataType.toLowerCase() ) {   
  151.             case "array" :   
  152.               //  Return value is resultSet   
  153.               bindItems(items);   
  154.               break;   
  155.             case "string" :   
  156.               //  Return value is string   
  157.               bindText(items[0].childNodes[0].firstChild.nodeValue);   
  158.           }   
  159.         } else {   
  160.           var htmlCode = request.responseText;   
  161.           bindText(htmlCode);   
  162.         }   
  163.       } else {   
  164.         //  Received data error   
  165.         alert("Not able to retrieve description " + request.statusText);   
  166.       }   
  167.     }   
  168.   }   
  169.       
  170.   /*   
  171.   *  Ajax callback function when Synchronous   
  172.   */   
  173.   function processRequestWhenSync() {   
  174.     if ( request.responseXML.documentElement != null ) {   
  175.       var xmlDoc = request.responseXML.documentElement;   
  176.       var xmlRoot = xmlDoc.getElementsByTagName("dataType");   
  177.       var dataType = xmlRoot[0].childNodes[0].firstChild.nodeValue;   
  178.       var items = xmlDoc.getElementsByTagName('item');   
  179.       switch ( dataType.toLowerCase() ) {   
  180.         case "array" :   
  181.           //  Return value is resultSet   
  182.           bindItems(items);   
  183.           break;   
  184.         case "string" :   
  185.           //  Return value is string   
  186.           bindText(items[0].childNodes[0].firstChild.nodeValue);   
  187.       }   
  188.     } else {   
  189.       var htmlCode = request.responseText;   
  190.       bindText(htmlCode);   
  191.     }   
  192.   }   
  193.       
  194.   //  Send request by ajax as Synchronous and medthod is GET   
  195.   function getWithSync() {   
  196.     sendRequestByAjax("GET"false);   
  197.     //  Operate request data   
  198.     processRequestWhenSync();   
  199.   }   
  200.       
  201.   //  Send request by ajax as Asynchronous and medthod is GET   
  202.   function getWithAsync() {   
  203.     sendRequestByAjax("GET"true);   
  204.   }   
  205.       
  206.   //  Send request by ajax as Synchronous and medthod is POST   
  207.   function postWithSync() {   
  208.     sendRequestByAjax("POST"false);   
  209.     //  Operate request data   
  210.     processRequestWhenSync();   
  211.   }   
  212.       
  213.   //  Send request by ajax as Asynchronous and medthod is POST   
  214.   function postWithAsync() {   
  215.     sendRequestByAjax("POST"true);   
  216.   }   
  217.       
  218.   /*   
  219.     *  Analyze form elements data   
  220.     *  @param  formElement  FormObject   
  221.     */   
  222.   function encodeFormData(formElement) {   
  223.     var whereClause = "";   
  224.     var and = "";   
  225.     var elementCount = formElement.length;   
  226.     for ( i = 0 ; i < elementCount ; i++ ) {   
  227.       var element = formElement[i];   
  228.       if ( element.name != "" ) {   
  229.         if (element.type=='select-one') {   
  230.           element_value = element.options[element.selectedIndex].value;   
  231.         } else if ( element.type == 'checkbox' || element.type == 'radio' ) {   
  232.           if ( element.checked == false ) {   
  233.             break;      
  234.           }   
  235.           element_value = trim(element.value);   
  236.         } else {   
  237.           element_value = trim(element.value);   
  238.         }   
  239.         whereClause += and + trim(element.name) + '=' + element_value.replace(/\&/g,"%26");   
  240.         and = "&"   
  241.       }   
  242.     }   
  243.     return whereClause;   
  244.   }   
  245.       
  246.   /*   
  247.     *  Bind text value   
  248.     */   
  249.   function bindText(value) {   
  250.     var elem = $(this.bindElementId)[0];   
  251.     //  Analyze object classification   
  252.     switch ( elem.tagName.toLowerCase() ) {   
  253.     case "div":   
  254.     case "span":   
  255.     case "textarea":   
  256.       elem.innerHTML += value;   
  257.       break;   
  258.     case "input":   
  259.       elem.value = value;   
  260.       break;   
  261.       default:   
  262.         alert("Can't bind data to element!");   
  263.         return false;   
  264.     }   
  265.     return true;   
  266.   }   
  267.  
  268.   /*   
  269.     *  Bind resultSet   
  270.     */   
  271.   function bindItems(items) {   
  272.     var elem = $(this.bindElementId)[0];   
  273.     //  Check the bind object is support   
  274.     if ( elem.tagName.toLowerCase() != "select" && elem.tagName.toLowerCase() != "ul" ) {   
  275.       alert("Can't bind data to element!");   
  276.       return;   
  277.     }   
  278.     //  Bind data to select   
  279.     if ( elem.tagName.toLowerCase() == "select" ) {   
  280.       var childCount = elem.childNodes.length;   
  281.       while ( childCount > 0 ) {   
  282.         //  Clear all values when the values is exists   
  283.         elem.removeChild(elem.childNodes[0]);   
  284.         childCount--;   
  285.       }   
  286.       // Bind data      
  287.       var itemCount = items.length;   
  288.       for ( var i = 0; i < itemCount; i++ ) {   
  289.         var option = document.createElement("OPTION");   
  290.         var Data = items[i];   
  291.            
  292.         option.value = Data.childNodes[0].firstChild.nodeValue;   
  293.         option.text = Data.childNodes[1].firstChild.nodeValue;   
  294.            
  295.         elem.options.add(option);   
  296.       }   
  297.     } else if ( elem.tagName.toLowerCase() == "ul" ) {   
  298.       //  Bind data to ul   
  299.       elem.innerHTML = "";   
  300.       // bind data   
  301.       var itemCount = items.length;   
  302.       for ( var i = 0; i < itemCount; i++ ) {   
  303.         var Data = items[i];   
  304.         var urlAddress = Data.childNodes[0].firstChild.nodeValue;   
  305.         var showText = Data.childNodes[1].firstChild.nodeValue;   
  306.         var innerCode = "
  307.  + urlAddress + "\" title=\"" + showText + "\">" + showText + "";   
  308.         elem.innerHTML += innerCode;   
  309.       }   
  310.     }   
  311.     return true;   
  312.   }   
  313.       
  314.   /*   
  315.   *  Submit form as Ajax   
  316.   *  @param  syncStatus:  true-Send ajax request by Asynchronous  false-Send ajax request by Synchronous   
  317.   * @param  formId:      the id is where form will submit   
  318.   *  @param  elementId:  the return value will bind for this element   
  319.   *   
  320.   */   
  321.   this.submitForm = function(syncStatus, formId, elementId) {   
  322.     var formElement = $(formId)[0];   
  323.     if ( formElement ) {   
  324.       setURL(formElement.getAttributeNode("action").value);   
  325.       setFormId(formId);   
  326.       setBindElementId(elementId);   
  327.       if ( syncStatus ) {   
  328.         if ( formElement.medthod.toUpperCase() == "POST" ) {   
  329.           postWithSync();   
  330.         } else if ( formElement.medthod.toUpperCase() == "GET" ) {   
  331.           getWithSync();   
  332.         } else {   
  333.           alert("Form medthod was not support! The form medthod is: " + formElement.medthod);   
  334.         }   
  335.       } else {   
  336.         if ( formElement.medthod.toUpperCase() == "POST" ) {   
  337.           postWithAsync();   
  338.         } else if ( formElement.medthod.toUpperCase() == "GET" ) {   
  339.           getWithAsync();   
  340.         } else {   
  341.           alert("Form medthod was not support! The form medthod is: " + formElement.medthod);   
  342.         }   
  343.       }   
  344.     } else {   
  345.       alert("Form is undefined!");   
  346.     }   
  347.   }   
  348.       
  349.   /*   
  350.   *  Get url address data as Ajax   
  351.   *  @param  syncStatus:  true-Send ajax request by Asynchronous  false-Send ajax request by Synchronous   
  352.   * @param  urlAddress:  the request url   
  353.   *  @param  elementId:  the return value will bind for this element   
  354.   *   
  355.   */   
  356.   this.getData = function(syncStatus, urlAddress, elementId) {   
  357.     setURL(urlAddress);   
  358.     setBindElementId(elementId);   
  359.     if ( syncStatus ) {   
  360.       getWithAsync();   
  361.     } else {   
  362.       getWithSync();   
  363.     }   
  364.   }   
  365. }   
  366.  
  367. //  Demo for request more times   
  368. function testRequestAsync() {   
  369.   /*   
  370.   *  request by Asynchronous   
  371.   */   
  372.   var ajaxRequest = new AjaxObject();   
  373.   var count = 10;   
  374.   var i = 0;   
  375.   while( i < count ) {   
  376.     ajaxRequest.getData(false"http://www.google.com/""test");   
  377.     i++;   
  378.   }   
  379. }   
  380.  
  381. //  Demo for request more times   
  382. function testRequestSync() {   
  383.   /*   
  384.   *  request by Synchronous   
  385.   */   
  386.   var count = 10;   
  387.   var i = 0;   
  388.   while( i < count ) {   
  389.     var ajaxRequest = new AjaxObject();   
  390.     ajaxRequest.getData(false"http://www.google.com/""test");   
  391.     i++;   
  392.   }   
  393. }  

以上就是这个通用Ajax框架的源代码。本文出自 “玄武·巴依” 博客。

【编辑推荐】

  1. 流行的AJAX框架对比:jQuery,Mootools,Dojo,Ext JS
  2. ASP.NET AJAX框架调用后台代码的基本方法
  3. 详解如何实现最基本的AJAX框架
  4. WCF初试 用JQuery实现loading的功能
  5. 学习jQuery必须知道的几种常用方法
责任编辑:yangsai 来源: 51CTO博客
相关推荐

2021-08-17 05:57:56

数据分析数据分析师工具

2021-03-29 11:20:39

前端代码工作流

2020-10-19 10:35:43

iOS设备尺寸

2018-08-31 08:42:48

LinuxUnix实用程序

2014-12-02 10:02:21

Android异步任务

2023-03-03 17:00:00

部署Linux内核

2019-10-11 15:58:25

戴尔

2021-05-27 07:12:19

单点登录系统

2024-02-20 08:56:50

JavaScript模块打包器

2016-06-07 14:25:50

逆向思维JS框架需求

2016-06-06 13:55:53

JS框架符合实际需求

2010-06-09 17:00:43

UML试题

2020-12-08 08:12:14

SQL脚本行转列

2022-02-25 09:00:00

数据科学工具架构

2023-01-29 16:15:59

开源代码

2010-12-24 11:27:13

华为HCNE认证

2020-06-30 15:33:05

Linux 系统 数据

2021-11-30 14:52:41

鸿蒙HarmonyOS应用

2022-05-13 14:56:03

人工智能DeepMind

2021-05-06 11:06:52

人工智能语音识别声闻检索
点赞
收藏

51CTO技术栈公众号