一套通用Ajax框架的源代碼
本次的Ajax框架代碼中沒有關(guān)于實現(xiàn)瀏覽器前進(jìn)、后退按鈕的處理,如果各位需要,可以從我原來的文章中獲取相應(yīng)的代碼。
聲明:本文中的所有代碼遵守GNU GPLv2的協(xié)議,對代碼進(jìn)行開源
發(fā)行注記:
2009/06/22
1、取消很多不必要的參數(shù)
2、代碼風(fēng)格更加面向?qū)ο?BR>3、允許用戶對request請求方式進(jìn)行設(shè)置(即用戶可以選擇同步或異步執(zhí)行Ajax請求)
4、框架使用閉包封裝
5、改進(jìn)了程序的執(zhí)行性能
JavaScript代碼中提供了兩個Demo函數(shù),分別是使用同步、異步對同一個URL進(jìn)行多次請求。
如果各位對這套框架有什么意見或建議,可以直接聯(lián)系我,在代碼的版權(quán)信息內(nèi),有本人的電子郵件地址
- /*
 - * 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++;
 - }
 - }
 
以上就是這個通用Ajax框架的源代碼。本文出自 “玄武·巴依” 博客。
【編輯推薦】















 
 
 












 
 
 
 