为什么要使用Ajax

为什么要使用Ajax呢,使用表单提交不是很好吗?

所以我们得先说说两者的区别?

普通的表单提交,页面会发生跳转,最简单的例子就是登录,比如""开源中国社区"的登录:
为什么要使用Ajax
 输入登录邮箱和登录密码,点击[现在登录]就会发生页面的跳转,进入到了如下页面:
为什么要使用Ajax
 

如果是Ajax呢?
为什么要使用Ajax
 

当我在"用户名"输入框输入"whuang"时,它提示我"此用户名已被注册,请另换一个",它是怎么知道我已经注册过"whuang"呢?因为它请求了一次服务器,但是界面却没有跳转.

而我登录的时候,请求了服务器,界面发生了跳转,这就是两者的区别.

说的让人听不懂一些,普通的请求是同步的,而Ajax是异步的.

为什么要使用Ajax?

因为用户体验,跳转的用户体验是很差的,屏幕会闪一下,而且填写的信息容易丢失.而使用Ajax的话,页面不跳转,之前填写的信息也都在.

那么如何实现Ajax呢?

以我两年前做的一个考试系统为例.

在管理员界面有一个全局设置页面,如下:
为什么要使用Ajax
 点击[生效]按钮,会请求服务器,但是页面不会发生跳转.比如在"试卷总分"输入框输入50,然后点击[生效]按钮
为什么要使用Ajax
 确实请求了服务器,我们可以看下后台的打印信息:
为什么要使用Ajax
 全局设置页面(globalSettings.jsp)代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="com.kingbase.web.util.ExamUtil"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/Ajax.js" ></script>
<script type="text/javascript" src="js/Module.js" ></script>
<script type="text/javascript" src="js/common_util.js" ></script>
<link href="css/main.css" type="text/css" rel="stylesheet">
<script type="text/javascript">
window.onload=function(){
	var sizePerPage=document.forms[0].size_per_page;
	//exam_sum_score.value="";
	
	var abc44=function (obj) {
		//alert(obj);
		if(obj!='no'){
			arr=obj.split("::");//obj="yes::0::0::2::fadf::"

			sizePerPage.value=arr[1];
			var examSumScore=document.forms[0].exam_sum_score;
			examSumScore.value=arr[2];
			showExamSwitch(arr[3]);
			if(arr[4]!='null'){
				loadInstruction(arr[4]);
			}
		}
	};
	var url2="<%=basePath%>/ViewWholeVariableServlet";
	//alert(url2);
	var xmlhw5=new XMLHttpHuangWei(url2, null,abc44);
	xmlhw5.XMLGetMethod();
	/****************** set exam switch start  ********************/
	//showExamSwitch();
	/****************** set exam switch end  ********************/
	
	//loadInstruction();
	//var examInstructionContent=document.forms[0].examInstructionContent;
	//examInstructionContent.disabled="disabled";
	//examInstructionContent.readOnly="readonly";
};
function showExamSwitch(exam_switch){
	var isExamTime=document.forms[0].isExamTime;
	com.whuang.hsj.setCheckedRadioByValue(isExamTime,exam_switch);
}

function setExamInstruction(){
	//var examInstructionBtn=document.forms[0].examInstructionBtn;
	var examInstructionContent=document.forms[0].examInstructionContent;
	if(com.whuang.hsj.isReadOnly(examInstructionContent)){
		alert("请先编辑,再提交修改!");
		return ;
	}
	abc4=function (obj) {
		alert("修改成功!");
	};

	var url2="AddExamInstructionServlet";
	var args3="isEdit=2&content="+examInstructionContent.value;
	var xmlhw5=new XMLHttpHuangWei(url2, args3,abc4);
	xmlhw5.XMLPostMethod();
	examInstructionContent.readOnly=true;
	examInstructionContent.disabled="disabled";
};
function loadInstruction(exam_instru){
	//var editInstructionContentBtn=document.forms[0].editInstructionContentBtn;
	var examInstructionContent=document.forms[0].examInstructionContent;
	examInstructionContent.readOnly=true;
	examInstructionContent.disabled="disabled";
	examInstructionContent.value =exam_instru;
	
	//examInstructionContent.disabled=false;
}

function shutdownExam(){
	//var shudownBtn=document.forms[0].shudownBtn;
	var isExamTime=document.forms[0].isExamTime;
	var value23=com.whuang.hsj.getRadioValue(isExamTime);
	abc4=function (obj) {
		alert("修改成功!");
	};
	var url2="SetExamSwitchServlet";
	var args3="isExamTime="+value23;
	var xmlhw5=new XMLHttpHuangWei(url2, args3,abc4);
	//alert(resultArray.result);
	xmlhw5.XMLPostMethod();
}

function setPageSize(){
	alert("该功能暂未实现.");
};

function setExamSumScore(){
	//var setExamScoreBtn=document.forms[0].setExamScoreBtn;
	var exam_sum_score=document.forms[0].exam_sum_score;
	abc4=function (obj) {
		alert("修改成功!");
	};
	var url2="SetExamSumScoreServlet";
	var args3="examSumScore="+exam_sum_score.value;
	var xmlhw5=new XMLHttpHuangWei(url2, args3,abc4);
	xmlhw5.XMLPostMethod();
}
function setPageSize(){
	var sizePerPage=document.forms[0].size_per_page;
	abc4=function (obj) {
		alert("修改成功!");
	};
	var url2="<%=basePath%>/SetSizePerPageServlet";
	var args3="sizePerPage="+sizePerPage.value;
	var xmlhw5=new XMLHttpHuangWei(url2, args3,abc4);
	xmlhw5.XMLPostMethod();
}
function viewInstruction(){
	var examInstructionContent=document.forms[0].examInstructionContent;
	abc4=function (obj) {
		examInstructionContent.value=obj;
	examInstructionContent.disabled="disabled";
		examInstructionContent.readOnly=true;
	};

	var url2="AddExamInstructionServlet";
	var args3="isEdit=1";
	var xmlhw5=new XMLHttpHuangWei(url2, args3,abc4);
	xmlhw5.XMLPostMethod();
}

function editInstruction(){
	var examInstructionContent=document.forms[0].examInstructionContent;
	examInstructionContent.readOnly=false;
	examInstructionContent.disabled="";
}
</script>

</head>
<body>
<center>
<h1>全局设置</h1><a  class="hyperlink" href="javascript:location.reload();" >刷新</a>
<form action="">
<table border="1" >
<tr><td>每页显示条数</td><td><input type="text" name="size_per_page" >  </td><td><input type="button" value="生效" onclick="setPageSize();" > </td>  </tr>
<tr><td>试卷总分</td><td><input type="text" name="exam_sum_score" >  </td><td><input type="button" name="setExamScoreBtn" value="生效" onclick="setExamSumScore();" > </td>  </tr>
<tr><td>是否打开考试功能</td><td><input name="isExamTime" type="radio" value="1" checked="checked" >打开 &nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="isExamTime"  value="2" >关闭 </td><td><input type="button" name="shudownBtn" onclick="shutdownExam();" value="生效" > </td> </tr>
<tr><td rowspan="2">考试说明</td><td colspan="2" ><textarea cols="50" readonly="readonly" rows="10" name="examInstructionContent"  ></textarea> </td></tr>

<tr > <td colspan="2" ><input name="editInstructionContentBtn" onclick="editInstruction();" type="button" value="编辑" > 
<input name="viewInstructionContentBtn" onclick="viewInstruction();" type="button" value="取消" >
<input type="button"  value="提交修改" name="examInstructionBtn" onclick="setExamInstruction();" > </td> </tr>
</table>
</form>
</center>
</body>
</html>

 详细讲解如下

刚才我点击[生效]触发的方法如下:

function setExamSumScore(){
	//var setExamScoreBtn=document.forms[0].setExamScoreBtn;
	var exam_sum_score=document.forms[0].exam_sum_score;
	abc4=function (obj) {
		alert("修改成功!");
	};
	var url2="SetExamSumScoreServlet";
	var args3="examSumScore="+exam_sum_score.value;
	var xmlhw5=new XMLHttpHuangWei(url2, args3,abc4);
	xmlhw5.XMLPostMethod();
}

 XMLHttpHuangWei 有三个参数,第一个参数是请求的服务器地址(接口地址),第二个参数是请求的参数,第三个参数是回调函数(回调方法).使用XMLHttpHuangWei需要引入如下文件Ajax.js,

XMLHttpHuangWei有两个方法XMLPostMethod(post方式请求) 和XMLGetMethod(get方式请求),

给一个get方式 请求的例子:

var abc44=function (obj) {
		if(obj!='no'){
			arr=obj.split("::");//obj="yes::0::0::2::fadf::"

			sizePerPage.value=arr[1];
			var examSumScore=document.forms[0].exam_sum_score;
			examSumScore.value=arr[2];
			showExamSwitch(arr[3]);
			if(arr[4]!='null'){
				loadInstruction(arr[4]);
			}
		}
	};
	var url2="<%=basePath%>/ViewWholeVariableServlet?name=whuang";

	var xmlhw5=new XMLHttpHuangWei(url2, null,abc44);
	xmlhw5.XMLGetMethod();

Ajax.js源代码如下

// return parameter
var xhr =null;
var ii=0;
var getXHR=null;
var objectXHR=null;
var responseMethod222222222111221;
var browser=navigator.appName;
var isIE=(browser=="Microsoft Internet Explorer");
var createXHR=function() {
	var xhr;
	try {
		xhr =xhr = new XMLHttpRequest();
		return xhr;
	} catch (e) {
		try {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
			return xhr;
		} catch (ee) {
			xhr = false;
		}
	}
	if (!xhr && typeof XMLHttpRequest != 'undefined') {
		 new ActiveXObject("Msxml2.XMLHTTP");
		return xhr;
	}
};

var onreadystatechangeMethod = function() {
	var copyObj=document.getElementById("copy");
	var obj = objectXHR;//		
	var isExist=(null!=copyObj);
	if (obj.readyState == 0) {
		if(isExist)
		copyObj.innerHTML = "Sending Request...";
	}
	if (obj.readyState == 1) {
		if(isExist)
		copyObj.innerHTML = "Loading Response...";
	}
	if (obj.readyState == 2) {
		if(isExist)
		copyObj.innerHTML = "Response Loaded...";
	}
	if (obj.readyState == 3) {
		if(isExist)
		copyObj.innerHTML = "Response Ready...";
	}
	if (obj.readyState == 4) {
		if (obj.status == 200) {
			//alert("this : "+this);//this direct to window
			if(isExist)
			copyObj.innerHTML = "Response Complete...";
			window.flag = true;
			var response = obj.responseText;
			//resultArray.result=response;
			if (!(responseMethod222222222111221 == null || responseMethod222222222111221 == undefined)) {
				responseMethod222222222111221(response);
				//alert(response+": "+(ii++));
			}
//			this.result.push(response);
			// alert("xmlhw.result:"+xmlhw.result);

		} else if (obj.status == 404) {
			alert(404);
			if(null!=copyObj)
			copyObj.innerHTML = "File not found";
		} else {
			if(null!=copyObj)
			copyObj.innerHTML = "There was a problem retrieving the XML.";
		}
	}
};

objectXHR=createXHR();

function XMLHttpHuangWei(url, arges, responseMethod2) {
	//objectXHR=;
	responseMethod222222222111221=responseMethod2;
	objectXHR=createXHR();
	//alert(this.xhr1);
	this.url = url;
	argObject = new Object();
	argObject.arg = arges;
	this.argesArray = argObject;
	this.method = responseMethod222222222111221;
	this.result = new Array();
	getXHR=function(){
		return window.objectXHR;
		//return createXHR();
	};
	

	this.XMLGetMethod = function() {
		getXHR().onreadystatechange = onreadystatechangeMethod;
		var args23="";
		if(this.argesArray.arg!=null&&this.argesArray.arg!=""){
			args23=this.argesArray.arg+"&";
		}
		getXHR().open("GET", this.url + '?' + args23+"timestamp=" + (new Date()).getTime()+"&isIE="+isIE , true);
		getXHR().send(null);
	};
	this.XMLPostMethod = function() {// xmlObj
	// alert("responseMethod:\n"+responseMethod);
	// alert("method:\n"+this.method);
		getXHR().onreadystatechange = onreadystatechangeMethod;
		getXHR().open("POST", this.url, true);
		getXHR().setRequestHeader('Content-type',
				'application/x-www-form-urlencoded');
		getXHR().send(this.argesArray.arg);
		// alert(this.argesArray.arg);
		//		
	};
}

相关推荐