在第二节中,介绍了简单的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