一、编写异步Action代码
二、在struts.xml中配置Action
三、编写异步jsp页面
四、测试
[url=http://www.cnblogs.com/qiantuwuliang/archive/2009/07/19/1526687.html]escape()、encodeURI()、encodeURIComponent()区别详解[/url]
/**
* Ajax1Action.java
* action
* Function: TODO
*
* version date author
* ──────────────────────────────────
* 1.0 2013-9-21 songjy
*
* Copyright (c) 2013, TNT All Rights Reserved.
*/
package action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* ClassName:Ajax1Action
*
* @author songjy
* @version 1.0
* @since v1.0
* @Date 2013-9-21 下午4:24:10
*/
public class Ajax1Action extends ActionSupport {
private static final long serialVersionUID = 2507057616433321827L;
private static List<String> names = new ArrayList<String>();
static {
names.add("song");
names.add("li");
}
public String check_name() throws IOException {
//非IoC方式获取HttpServletResponse
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/plain; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(names.contains(name));
out.flush();
out.close();
return null;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/*备注:
* 1、IoC方式也可获取HttpServletResponse,需要实现org.apache.struts2.interceptor.ServletResponseAware接口,
* 但不推荐,因实现麻烦且与Servlet API耦合大。
*/
二、在struts.xml中配置Action
<action name="*" class="action.Ajax1Action" method="{1}"/>
三、编写异步jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<title>AJAX示例</title>
<script type="text/javascript">
function check_name() {
var username = encodeURIComponent($("#username").val());
$.post("<%=basePath%>/check_name.do", {
name : username
}).done(function(data) {
alert("Data Loaded: " + data);
});
}
</script>
</head>
<body>
姓名:<input type="text" name="username" id="username" onblur="javascript:check_name();">
</body>
</html>
四、测试
[url=http://www.cnblogs.com/qiantuwuliang/archive/2009/07/19/1526687.html]escape()、encodeURI()、encodeURIComponent()区别详解[/url]