实现异步通信,用json与jquery实现起来相当简便。
Struts2整合jQuery
Struts2中主要的业务操作都是通过Action来完成的,此时就需要jQuery来访问Struts2的Action:
$.post("Action",……)
1.1 registe.jsp页面:
功能:用户注册,首先输入用户名:
正确:用户名没有被注册,你可以使用;
错误:用户名已经被注册;
1.2 jQuery代码:
function checkkey() { var url = 'showAllInstitute.action'; var params = {companyKey:$('#ckey').attr('value')}; jQuery.post(url, params, callbackFun); } function callbackFun(data) { $('#warn').html(data); //显示返回的数据 }
1.3 HTML:当文本框失去焦点时,触发回调事件。
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <script language="JavaScript" src="js/jquery-1.6.3.js"></script> <script type="text/javascript" src="js/jquery.js"></script> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'jquery.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <DIV class=line><LABEL class=big id=lblName>用户注册</LABEL> <INPUT id='ckey' name="ckey" onblur="checkkey();"><span id="warn"></span> </DIV> </body> </html>
说明:
1)当文本框‘ckey’失去焦点时:调用“checkkey”函数;
2) “checkkey”函数分别确定两个信息:
3) 异步访问:'showAllInstitute.action'——判断标识是否正确的Action类。
4)参数:{companyKey:$('#ckey').attr('value')},一个以json格式拼写的参数。
5)发出异步请求:jQuery.post(url, params, callbackFun);
json格式如下:
1.4 Action代码:
public String queryAllInstitutes() { try { String remessage; if("jquery".equals(companyKey)) remessage="用户名已经被注册"; else remessage="用户名没有被注册,您可以使用此用户名"; HttpServletResponse response = ServletActionContext.getResponse(); //response.setContentType("text/html"); //火狐浏览器必须加上这句 response.setCharacterEncoding("UTF-8"); response.getWriter().write(remessage); } catch (Throwable e) { e.printStackTrace(); } return null; }
如果是火狐浏览器记得加上上面的那句,否则出现下面错误:
1.5 struts.xml中的配置
<action name="showAllInstitute" class="net.hncu.struts2.action.ShowAllInstituteAction" method="queryAllInstitutes"> <!-- 定义处理结果与视图资源之间的关系--> </action>
备注:
返回值:XMLHttpRequestjQuery.post(url, [data],[callback],[type])
概述
通过远程 HTTP POST 请求载入信息。
这是一个简单的 POST 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。
参数
url,[data],[callback],[type]String,Map,Function,StringV1.0
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
示例
1描述:
请求 test.php 网页,忽略返回值:
jQuery 代码:
$.post("test.php");
2描述:
请求 test.php 页面,并一起发送一些额外的数据(同时仍然忽略返回值):
jQuery 代码:
$.post("test.php", { name: "John", time: "2pm" } );
3描述:
向服务器传递数据数组(同时仍然忽略返回值):
jQuery 代码:
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
4描述:
使用 ajax 请求发送表单数据:
jQuery 代码:
$.post("test.php", $("#testform").serialize());
5描述:
输出来自请求页面 test.php 的结果(HTML 或 XML,取决于所返回的内容):
jQuery 代码:
$.post("test.php", function(data){
alert("Data Loaded: " + data);
});
6描述:
向页面 test.php 发送数据,并输出结果(HTML 或 XML,取决于所返回的内容):
jQuery 代码:
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
7描述:
获得 test.php 页面的内容,并存储为 XMLHttpResponse 对象,并通过 process() 这个 JavaScript 函数进行处理:
jQuery 代码:
$.post("test.php", { name: "John", time: "2pm" },
function(data){
process(data);
}, "xml");
8描述:
获得 test.php 页面返回的 json 格式的内容::
jQuery 代码:
$.post("test.php", { "func": "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");