Ajax幾個簡單的案例(ajax_使用者唯一驗證、ajax_返回xml資料的處理(包括分頁處理)
Ajax幾個簡單的案例(ajax_使用者唯一驗證、ajax_返回xml資料的處理(包括分頁處理)
當然開發的前提是把相應的包匯入專案中(開發環境myeclipse)
ajax_使用者唯一驗證(servlet):
如圖在myeclipse中的ajax_servlet專案中的index.jsp實現頁面的顯示:
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
<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/
-->
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/util.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/user/reg.js"></script>
</head>
<body>
<div align="center">
<form action="">
使用者名稱:<input type="text" id="uname" /><span id="cname"></span><br>
密碼:<input type="password" id="upass" /><br><input
type="submit" value="註冊" />
</form>
</div>
</body>
</html>
然後在webroot下新建一個js資料夾,這個裡面寫我們的js程式碼實現ajax使用
在util.js中封裝了傳送和接收的請求和一些必要的程式碼
Util.js檔案程式碼:
//通過id獲取dom物件
function $(id){
return document.getElementById(id);
}
//建立XMLHttpRequest物件
function createXHR(){
//宣告
var xhr;
//IE 瀏覽器XMLHTTP 元件的名稱
var aVertion =["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp.2.0","Microsoft.XMLHttp"];
try{
//firefox opera等瀏覽器
xhr=new XMLHttpRequest();
}catch(ex){
for (var i=0;i<aVertion.lengrh;i++){
try{
xmlHttpRequest=new ActiveXObject(aVersion[i]);
return xmlHttpRequest;
}catch(ex){
continue;
}
}
}
return xhr;
}
var xhr = createXHR();
function sendPost(content, url, success, fail) {
// ajax處理操作
// 建立xhr物件
// 觸發器
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
success(xhr);
} else {
fail(xhr);
}
}
};
// 開啟請求
xhr.open("POST", url, true);
// 設定型別
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 傳送請求
xhr.send(content);
}
然後再user下的reg.js中寫要完成的程式碼
Reg.js檔案程式碼:
window.onload=function(){
//獲取id="uname"節點物件
var unameDom=$("uname");
//為節點註冊onblur事件
unameDom.onblur=function(){
//根據value屬性獲取穿的的值並且拼成傳遞的引數
var content ="name="+unameDom.value;
//封裝請求的url路徑
var url="./servlet/regUser.do?time="+new Date().getTime();
sendPost(content, url, disposeSuccess, disposeFail);
function disposeSuccess(){
$("cname").innerHTML=xhr.responseText;
}
function disposeFail(){
alert("請求失敗");
}
};
};
最後在src下建立action處理方法
UserAction.java檔案程式碼:
package www.csdn.net.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
System.out.println("===="+name);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
if("xiao".equals(name)){
out.print("使用者已經存在");//輸出文字
}else{
out.print("使用者名稱可以使用");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
這樣就完成了,釋出到tomcat伺服器上然後用火狐瀏覽器測試就可以了
ajax_使用者唯一驗證(struts2)
如圖所示;
首先實現頁面的程式碼:
Index.jsp檔案程式碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/util.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/user/reg.js"></script>
</head>
<body>
<div align="center">
<h3>註冊頁面</h3>
</div>
<div align="center">
<s:form action="regUser" namespace="/csdn" theme="simple">
使用者名稱:<s:textfield name="usernaem" id="uname" />
<span id="cname"></span>
<br>
密碼:<s:textfield name="userpass" id="upass" />
<br>
郵箱:<s:textfield name="useremial" id="uemail" />
<br>
<s:submit value="註冊" />
</s:form>
</div>
</body>
</html>
Sc.jsp檔案程式碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/util.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/user/reg.js"></script>
</head>
<body>
。。。。。。。。。
</body>
</html>
然後是js檔案
Util.js檔案程式碼:
//通過id獲取dom物件
function $(id){
return document.getElementById(id);
}
//建立XMLHttpRequest物件
function createXHR(){
//宣告
var xhr;
//IE 瀏覽器XMLHTTP 元件的名稱
var aVertion =["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp.2.0","Microsoft.XMLHttp"];
try{
//firefox opera等瀏覽器
xhr=new XMLHttpRequest();
}catch(ex){
for (var i=0;i<aVertion.lengrh;i++){
try{
xmlHttpRequest=new ActiveXObject(aVersion[i]);
return xmlHttpRequest;
}catch(ex){
continue;
}
}
}
return xhr;
}
Reg.js檔案程式碼:
window.onload=function(){
//獲取id="uname"節點物件
var unameDom=$("uname");
//為節點註冊onblur事件
unameDom.onblur=function(){
//根據value屬性獲取穿的的值並且拼成傳遞的引數
var content ="name="+unameDom.value;
//封裝請求的url路徑
var url="./csdn/UserAction_checkName.action?time="+new Date().getTime();
//獲取建立的xhr物件(XMLHTTPRequest物件)
var xhr=createXHR();
//事件處理函式觸發器
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//狀態碼返回4處理完畢(這樣才能使用xhr.responseText獲取返回的結果)
if(xhr.status==200 || xhr.status==304){//伺服器返回的狀態碼200一切ok304伺服器沒有被修改
//ajax請求之後再這裡做相應的處理
$("cname").innerHTML=xhr.responseText;
//如果接收的是XML檔案就用responseXML;
}
}
};
//開啟請求
xhr.open("POST",url,true);
//如果用POST請求向伺服器傳送資料,需要將“Content-type”的首部
//設定為“application/x-www-form-urlencoded”它會告知伺服器正在傳送資料,並且資料已經符合URL編碼了
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//傳送請求
xhr.send(content);
};
};
Struts.xml檔案程式碼:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<include file="www/csdn/project/resource/struts-constant.xml"/>
<package name="test" namespace="/csdn" extends="struts-default">
<action name="UserAction_*" class="www.csdn.project.action.UserAction" method="{1}">
<result name="reg" type="plainText">
<param name="location">/sc.jsp</param>
<param name="charSet">UTF-8</param>
</result>
</action>
</package>
</struts>
最後UserAction.java檔案程式碼:
package www.csdn.project.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String checkName(){
HttpServletResponse response=ServletActionContext.getResponse();//獲取response物件
response.setContentType("text/html;charset=utf-8");//設定相應文件型別
PrintWriter out=null;//宣告輸出的out物件
try {
out=response.getWriter();//根據response物件獲取out物件
} catch (IOException e) {
e.printStackTrace();
}
if("xiao".equals(name)){
out.print("使用者已經存在");//輸出文字
}else{
out.print("使用者名稱可以使用");
}
out.flush();//立即寫入
out.close();//關閉
return "reg";
}
}
ajax_返回xml資料的處理(包括分頁)(資料庫自己建立,在DAO層和service層實現用hibernate)
如圖專案結構
連線資料庫
資料庫在相應層實現就行
首先實現頁面的顯示
Index.jsp檔案程式碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<div align="center">
<a href="${pageContext.request.contextPath }/csdn/UserAction_login.action">進入後臺</a>
</div>
</body>
</html>
Cindex.jsp檔案程式碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="${pageContext.request.contextPath }/js/util.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/user/user_checkName.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/user/user_query.js"></script>
</head>
<body>
<div align="center">
<div style="border: 1px; width: 600px; height: 400px;">
<table width="300px">
<tr>
<td>
使用者名稱:
</td>
<td>
<s:textfield id="uname" name="username" theme="simple"></s:textfield>
</td>
<td style="color: red; font-size: 10px;" id="cname">
</td>
</tr>
<tr>
<td>
密碼:
</td>
<td>
<s:password id="upass" name="userpass" theme="simple"></s:password>
</td>
<td>
</td>
</tr>
<tr>
<td colspan="3" style="text-align: center;">
<s:a href="#" theme="simple">註冊</s:a>
</td>
</tr>
</table>
</div>
<div>
<span>不使用它</span>
<s:url id="user_query" namespace="/csdn" action="UserAction_query"></s:url>
<s:a href="%{user_query}">查詢所有使用者</s:a>
</div>
<br/><