模拟jQuery ajax服务器端与客户端通信的代码

2020-05-23 06:10:56易采站长站整理

doGet(request, response);
}
}

配置web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”2.4″ xmlns=”http://java.sun.com/xml/ns/j2ee”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>
<servlet>
<servlet-name>AjaxServer</servlet-name>
<servlet-class>com.ljq.test.AjaxServer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServer</servlet-name>
<url-pattern>/servlet/ajaxServer</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

index.jsp页面

<%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;
%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<base href=”<%=basePath%>”>
<title>My JSP ‘index.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”>
<script type=”text/javascript” src=”<%=request.getContextPath()%20%>/js/jquery-1.3.1.js”></script>
<script type=”text/javascript” src=”<%=request.getContextPath()%20%>/js/validate.js”></script>
</head>
<body>
<!–html5的标准: 首先标签名要小写,其次标签必须关闭,第三属性名遵循骆驼命名法,第四属性值必须位于双引号中–>
请输入用户名:<br/>
<input id=”userName”/>
<input type=”button” value=” 校 验 ” onclick=”verify();”/>
<div id=”result”></div>
</body>
</html>

validate.js

function verify() {
// 解决中文乱码方法一: 页面端发出的数据作一次encodeURI,服务器段使用new String(name.getBytes(“iso8859-1″),”UTF-8”);
// 解决中文乱码方法二: 页面端发出的数据作两次encodeURI,服务器段使用URLDecoder.decode(name,”UTF-8″)