在第二節中,介紹了簡單的DOM操作方法,接下來該到Ajax的傳統項目-xmlHttpRequest了。在使用xmlHttpRequest時,需要注意到編碼的問題,要讓dojo預設綁定為utf-8怎麼辦呢?很簡單,只需要修改一下引入dojo.js時的標籤:
<script type="text/javascript" src="./dojo-lib/dojo/dojo.js" djConfig="isDebug:true,bindEncoding:'UTF-8'"></script>
下面,我們用執行個體來說明dojo中如何使用xmlHttpRequest。
執行個體一:
功能:簡單的調用JSP頁面的內容,沒有參數的傳遞。
原始碼如下:
Html頁面,即首頁面
方法1:
<html>
<head>
<meta name="generator" content="HTML Tidy, see http://www.w3.org/">
<meta http-equiv="Content-Type" content= "text/html; charset=iso-8859-1">
<title>Dojo, xmlHttpRequest!</title>
<script type="text/javascript" src="dojoroot/dojo/dojo.js" djConfig="isDebug:true,bindEncoding:'UTF-8'">
</script>
</head>
<body>
<input id="hello" value="hello" type="button"/><input id="dropContent" value="This is my first page!" type="text"/>
<div id="divHello">
</div>
<script type="text/javascript">
function responsevalue(responseText){
alert(responseText);
dojo.byId("dropContent").value = responseText;
}
function responseError(response){
alert("Error");
}
function helloworld(){
dojo.xhrGet({
url: "test.jsp",
method: "Get",
handleAs: "text",
load: responsevalue,
error: responseError,
});
}
var first = dojo.byId("hello");
dojo.connect(first, "onclick", helloworld);
</script>
</body>
</html>
方法2:
<html>
<head>
<meta name="generator" content="HTML Tidy, see http://www.w3.org/">
<meta http-equiv="Content-Type" content= "text/html; charset=iso-8859-1">
<title>Dojo, xmlHttpRequest!</title>
<script type="text/javascript" src="dojo-0.3.1-ajax/dojo.js" djConfig="isDebug:true,bindEncoding:'UTF-8'">
</script>
</head>
<body>
<input id="hello" value="hello" type="button"/><input id="dropContent" value="This is my first page!" type="text"/>
<div id="divHello">
</div>
<script type="text/javascript">
function helloworld1(){
dojo.io.bind({
url: "test.jsp",
load: function(type, data, evt){
dojo.byId("divHello").innerHTML = data;
},
error: function(type, error){
alert(error);
}
});
}
var first = dojo.byId("hello");
dojo.event.connect(first, "onclick", helloworld1);
</script>
</body>
</html>
test.jsp頁面:
<%@ page contentType="text/html;charset=GB2312"%>
<%
String result =“Hello, Dojo, xmlHttpRequest !”;
out.print(result);
%>
輸出結果:運行Html頁面,點擊“hello”按鈕時,輸出結果為:Hello, Dojo, xmlHttpRequest !
執行個體二:
功能:調用JSP頁面的內容,如何傳遞參數。在執行個體一給出代碼中添加參數content即可。
原始碼如下:
Html頁面:
var params = {
username: 'feifei',
id: '20022458',
}
function helloworld(){
dojo.xhrGet({
url: "testparams.jsp",
content: params,
method: "Get",
handleAs: "text",
load: responsevalue,
error: responseError,
});
}
testparams.jsp頁面:
<%@ page contentType="text/html;charset=GB2312"%>
<%
String username = request.getParameter("username");
String password=request.getParameter("id");
String result =username;
result+= password;
out.print(result);
%>
輸出結果:運行Html頁面,點擊“hello”按鈕時,輸出結果為:feifei20022458