為什麼要使用ajax呢,使用表單送出不是很好嗎?
是以我們得先說說兩者的差別?
普通的表單送出,頁面會發生跳轉,最簡單的例子就是登入,比如""開源中國社群"的登入:

輸入登入郵箱和登入密碼,點選[現在登入]就會發生頁面的跳轉,進入到了如下頁面:
如果是ajax呢?
當我在"使用者名"輸入框輸入"whuang"時,它提示我"此使用者名已被注冊,請另換一個",它是怎麼知道我已經注冊過"whuang"呢?因為它請求了一次伺服器,但是界面卻沒有跳轉.
而我登入的時候,請求了伺服器,界面發生了跳轉,這就是兩者的差別.
說的讓人聽不懂一些,普通的請求是同步的,而ajax是異步的.
為什麼要使用ajax?
因為使用者體驗,跳轉的使用者體驗是很差的,螢幕會閃一下,而且填寫的資訊容易丢失.而使用ajax的話,頁面不跳轉,之前填寫的資訊也都在.
那麼如何實作ajax呢?
以我兩年前做的一個考試系統為例.
在管理者界面有一個全局設定頁面,如下:
點選[生效]按鈕,會請求伺服器,但是頁面不會發生跳轉.比如在"試卷總分"輸入框輸入50,然後點選[生效]按鈕
确實請求了伺服器,我們可以看下背景的列印資訊:
全局設定頁面(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;
examinstructioncontent.value =exam_instru;
//examinstructioncontent.disabled=false;
function shutdownexam(){
//var shudownbtn=document.forms[0].shudownbtn;
var value23=com.whuang.hsj.getradiovalue(isexamtime);
var url2="setexamswitchservlet";
var args3="isexamtime="+value23;
//alert(resultarray.result);
function setpagesize(){
alert("該功能暫未實作.");
function setexamsumscore(){
//var setexamscorebtn=document.forms[0].setexamscorebtn;
var exam_sum_score=document.forms[0].exam_sum_score;
var url2="setexamsumscoreservlet";
var args3="examsumscore="+exam_sum_score.value;
var url2="<%=basepath%>/setsizeperpageservlet";
var args3="sizeperpage="+sizeperpage.value;
function viewinstruction(){
examinstructioncontent.value=obj;
examinstructioncontent.readonly=true;
var args3="isedit=1";
function editinstruction(){
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>
詳細講解如下
剛才我點選[生效]觸發的方法如下:
xmlhttphuangwei 有三個參數,第一個參數是請求的伺服器位址(接口位址),第二個參數是請求的參數,第三個參數是回調函數(回調方法).使用xmlhttphuangwei需要引入如下檔案ajax.js,
xmlhttphuangwei有兩個方法xmlpostmethod(post方式請求) 和xmlgetmethod(get方式請求),
給一個get方式 請求的例子:
var abc44=function (obj) {
var url2="<%=basepath%>/viewwholevariableservlet?name=whuang";
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");
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) {
copyobj.innerhtml = "loading response...";
if (obj.readystate == 2) {
copyobj.innerhtml = "response loaded...";
if (obj.readystate == 3) {
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 {
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().open("post", this.url, true);
getxhr().setrequestheader('content-type',
'application/x-www-form-urlencoded');
getxhr().send(this.argesarray.arg);
// alert(this.argesarray.arg);
//