本次的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++;
- }
- }
以上就是这个通用Ajax框架的源代码。本文出自 “玄武·巴依” 博客。
【编辑推荐】