jQuery ajax請求struts action實現(xiàn)異步刷新
這個樣例是用JQuery ajax和struts來做的一個小樣例,在這個樣例中采用兩種方式將java Util中的list轉(zhuǎn)換成支json的格式,第一種是用json-lib.jar這個jar包來轉(zhuǎn)換,第二種是采用goole的gson-2.1.jar來轉(zhuǎn)換,大家可以根據(jù)需要導(dǎo)入相應(yīng)的jar包,在這里為了做測試將兩種jar包都導(dǎo)入了。下面開始進入正題
第一步:導(dǎo)入相關(guān)jar包,本樣例需導(dǎo)入struts相關(guān)jar包,json-lib.jar,gson-2.1.jar可以任意選擇,但是這里需要都導(dǎo)入,因為為了做測試,兩種jar包的轉(zhuǎn)換方式都用到了。
第二步:配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <!-- 聲明Struts2的前端控制器 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 聲明Spring的ContextListener,負責(zé)上下文一加載立即創(chuàng)建BeanFactory --> <context-param> <!-- 若applicationContext.xml沒有放在WEB-INF下或者不叫這個名字,必需聲明此參數(shù) --> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> </web-app>
第三步:新建struts.xml,默認admin/下跳轉(zhuǎn)到/WEB-INF/index.jsp
<?xml version="1.0" encoding="UTF-8" ?> <!-- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> --> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://www.yxccc.com/news/"> <struts> <package name="bg" namespace="/" extends="struts-default"> <default-action-ref name="index"/> <!-- =================基礎(chǔ)跳轉(zhuǎn)====================== --> <action name="index"> <result>/WEB-INF/index.jsp</result> </action> </package> </struts>
第四步:編寫AjaxRequestAction.java文件,這里做了兩種請求,一種是直接請求到字符串,另一種是請求到一組數(shù)組格式的數(shù)據(jù),但該數(shù)據(jù)必須要轉(zhuǎn)換成JSON支持的數(shù)組,具體如下
package com.fengqi.action; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import org.apache.struts2.ServletActionContext; import com.google.gson.Gson; import com.opensymphony.xwork2.ActionSupport; /** * 創(chuàng)建時間:2014-10-24,ajax請求的action樣例 */ public class AjaxRequestAction extends ActionSupport{ private String sex; @Override public String execute() throws Exception { return super.execute(); } /** * ajax請求,以json格式的字符串響應(yīng)請求 */ public void ajaxString(){ System.out.println(sex); //獲取相應(yīng)Response HttpServletResponse response = ServletActionContext.getResponse(); //設(shè)置編碼方式 response.setCharacterEncoding("UTF-8"); try { if(sex.equals("nan")){ response.getWriter().write("我是男的"); }else if(sex.equals("nv")){ response.getWriter().write("我是女的"); }else{ response.getWriter().write("男女都不是"); } //將數(shù)據(jù)寫到頁面中 } catch (IOException e) { e.printStackTrace(); } } /** * ajax請求,以list的形式響應(yīng)請求,主要這里的list并不是Util的List,而是經(jīng)過轉(zhuǎn)換成指出json格式的List */ public void ajaxList(){ List<Object> list = new ArrayList<Object>(); list.add("張三"); list.add("李四"); //第一種方法:利用json-lib包中的JSONArray將List轉(zhuǎn)換成JSONArray各式。 JSONArray jsonArray = JSONArray.fromObject(list); //第二周方法:利用goole的json包將List轉(zhuǎn)換成Json對象。 Gson gson = new Gson(); String gsonList = gson.toJson(list); //獲取相應(yīng)Response HttpServletResponse response = ServletActionContext.getResponse(); //設(shè)置編碼方式 response.setCharacterEncoding("UTF-8"); try { //將數(shù)據(jù)寫到頁面中 response.getWriter().println(jsonArray); } catch (IOException e) { e.printStackTrace(); } } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
第五步:在將struts.xml文件更新下,配置AjaxRequestAction.java的訪問路徑添加如下代碼
<package name="ajax" namespace="/ajax" extends="struts-default"> <!-- =================ajax請求跳轉(zhuǎn)====================== --> <action name="ajax_*" class="com.fengqi.action.AjaxRequestAction" method="ajax{1}"> </action> </package>
最后struts.xml的完整文件是
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://www.yxccc.com"> <struts> <package name="bg" namespace="/admin" extends="struts-default"> <default-action-ref name="index"/> <!-- =================基礎(chǔ)跳轉(zhuǎn)====================== --> <action name="index"> <result>/WEB-INF/index.jsp</result> </action> </package> <package name="ajax" namespace="/ajax" extends="struts-default"> <!-- =================ajax請求跳轉(zhuǎn)====================== --> <action name="ajax_*" class="com.fengqi.action.AjaxRequestAction" method="ajax{1}"> </action> </package> </struts>
第六步:編寫index.jsp文件,這里做了兩種請求,一種是直接請求到字符串,另一種是請求到一組數(shù)組格式的數(shù)據(jù),但該數(shù)據(jù)必須要轉(zhuǎn)換成JSON支持的數(shù)組,具體如下
<%@ 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%>" rel="external nofollow" > <title>ajax異步刷新樣例測試</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" /> <script src="js/jquery-2.1.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#hh1").click(function(){ $.ajax({ url:"ajax/ajax_String",//請求url data:{sex:$("#txt1").val()}, success:function(data){//請求返回的數(shù)據(jù) $("div").html(data);//將數(shù)據(jù)打印到頁面的div中 } }); }); $("#hh2").click(function() { $.ajax({ url: "ajax/ajax_List",//請求url http://www.yxccc.com //cache: false, type: "POST", //請求頭,這里是post datatype: 'json', //請求數(shù)據(jù)各式,這里是json格式 success: function(data,status){ data = $.parseJSON(data); //將字符串格式的數(shù)據(jù)轉(zhuǎn)換成json對象 //這里將option元素移除是考慮到如果在頁面不刷新的情況下多次請求,會產(chǎn)生數(shù)據(jù)累加,不符合業(yè)務(wù)需求,因此需先刪除在增加元素。 $("option").remove(); $("select").append("<option>請選擇</option>");//在select元素下添加option子元素。 $(data).each(function(i){ //遍歷請求相應(yīng)的data數(shù)據(jù) $("select").append("<option>"+data[i]+"</option>"); }) } }); }); }); </script> </head> <body> <br> <h2 align="center">這里是ajax請求Demo,該實例是請求Struts中的action</h2> <br> <button id="hh1">請求返回常規(guī)字符串</button> <button id="hh2">請求返回JSON格式的List</button><br><br> <div>這里是div元素</div><br> 請選擇性別:<select id="txt1" name="sex"> <option>請選擇</option> <option value="nan">男</option> <option value="nv">女</option> </select><br><br> <select> <option>select選擇</option> </select> </body> </html>
這樣一個簡單的ajax請求就已經(jīng)完成了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于jQuery中ajax的相關(guān)方法匯總(必看篇)
下面小編就為大家?guī)硪黄诨趈Query中ajax的相關(guān)方法匯總。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11jquery實現(xiàn)輸入框動態(tài)增減的實例代碼
主要功能是動態(tài)增減輸入框,而且支持對各個輸入框的檢測,每個輸入框在輸入內(nèi)容后,對其進行錯誤提示2013-07-07JQuery.Ajax()的data參數(shù)類型實例詳解
這篇文章主要介紹了JQuery.Ajax()的data參數(shù)類型實例詳解,需要的朋友可以參考下2015-11-11Jquery+WebService 校驗賬號是否已被注冊的代碼
在Javascirpt代碼中,調(diào)用Jquery的方法$.Ajax(function)實現(xiàn)Ajax,傳遞賬號信息給Web服務(wù),Web服務(wù)再調(diào)用數(shù)據(jù)庫操作類查詢數(shù)據(jù)庫,并返回數(shù)據(jù)給前臺頁面。2010-07-07