一套通用Ajax框架的源代码

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

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

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

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

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

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

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

前端代码工作流

2021-08-17 05:57:56

数据分析数据分析师工具

2025-02-27 10:25:35

组件库MatBlazorWeb

2020-10-19 10:35:43

iOS设备尺寸

2018-08-31 08:42:48

LinuxUnix实用程序

2023-03-03 17:00:00

部署Linux内核

2014-12-02 10:02:21

Android异步任务

2019-10-11 15:58:25

戴尔

2021-05-27 07:12:19

单点登录系统

2024-02-20 08:56:50

JavaScript模块打包器

2024-12-09 09:25:30

2016-06-07 14:25:50

逆向思维JS框架需求

2016-06-06 13:55:53

JS框架符合实际需求

2010-06-09 17:00:43

UML试题

2024-11-19 16:31:23

2022-02-25 09:00:00

数据科学工具架构

2024-11-12 08:13:09

2020-12-08 08:12:14

SQL脚本行转列

2023-01-29 16:15:59

开源代码

2010-12-24 11:27:13

华为HCNE认证
点赞
收藏

51CTO技术栈公众号