使用XMLHttpRequest結合struts2實現Ajax非同步呼叫的例子__Ajax

來源:互聯網
上載者:User

      自己在網上找資料的時候,確實很糾結呢,東拼西湊的,雖然這個寫的東西很簡單,但是卻花費我不少功夫,為了協助後面的同學,果斷貼代碼,希望對大家有用。

      功能描述:使用XMLHttpRequest實現非同步呼叫,從而實現select級聯下拉式功能表的效果。

      項目總貼截圖如下(主要是給大家看看引入的jar包):

Action類的代碼:

 

package com.action;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class AjaxTest1 extends ActionSupport {private Map<String,List<String>> datas;private List<String> provinces;private List<String> citys;public AjaxTest1(){datas = new HashMap<String,List<String>>();String[] c1 = new String[]{"武漢","襄樊","荊州","宜昌"};String[] c2 = new String[]{"海澱","昌平","朝陽"};datas.put("湖北", Arrays.asList(c1));datas.put("北京", Arrays.asList(c2));}public List<String> getProvinces() {return provinces;}public void setProvinces(List<String> provinces) {this.provinces = provinces;}public List<String> getCitys() {return citys;}public void setCitys(List<String> citys) {this.citys = citys;}public String loadProvinces(){List<String> list = new ArrayList<String>();Set<String> set = datas.keySet();for(String s:set){list.add(s);}System.out.println(list);this.setProvinces(list);System.out.println("provinces:"+provinces);return SUCCESS;}public String loadCitys(){String province = ServletActionContext.getRequest().getParameter("province");//this.setCitys(datas.get("湖北"));System.out.println("返回的province的值是:"+province);List<String> list = new ArrayList<String>();this.setCitys(datas.get(province));return SUCCESS;}}

struts.xml檔案:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"    "http://struts.apache.org/dtds/struts-2.0.dtd"><struts>   <constant name="struts.enable.DynamicMethodInvocation" value="false" />    <constant name="struts.devMode" value="true" />   <!--  <package name="default" namespace="/" extends="struts-default">        <default-action-ref name="index" />        <global-results>            <result name="error">/error.jsp</result>        </global-results>        <global-exception-mappings>            <exception-mapping exception="java.lang.Exception" result="error"/>        </global-exception-mappings>        <action name="index">            <result type="redirectAction">                <param name="actionName">HelloWorld</param>                <param name="namespace">/example</param>            </result>        </action>    </package>   <include file="example.xml"/>   Add packages here -->          <package name="test1" namespace="/" extends="json-default">     <action name="loadprovinces" class="com.action.AjaxTest1" method="loadProvinces">     <result name="success" type="json">     <!--<param name="includeProperties">provinces</param>     -->     <param name="excludeProperties">citys</param>     </result>     </action>          <action name="loadcitys" class="com.action.AjaxTest1" method="loadCitys">     <result type="json">     <param name="excludeProperties">provinces</param>     </result>     </action>     </package></struts>


index.jsp分頁檔:


 

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@taglib prefix="s" uri="/struts-tags" %><%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">//擷取XMLHttpRequest對象的方法function createXMLHttpRequest(){try{xhr = new XMLHttpRequest();}catch(e){var MSXML =['MSXML2.XMLHTTP.6.00','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'];for(var n=0;n<MSXML.length;n++){try{xhr = new ActiveXObject(MSXML[n]);break;}catch(e){}}}return xhr;}var xhr;//xhr= createXMLHttpRequest();function loadProvinces(){xhr = createXMLHttpRequest();xhr.open("post","loadprovinces.action",true);//xhr.open("post","ajaxtest1.jsp",true);xhr.setRequestHeader("Context-Type","application/x-www-form-urlencoded");xhr.send(null);xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200 || xhr.status == 304){var provinceString = eval("("+xhr.responseText+")");var pro = provinceString.provinces;//alert("provinceString[0]:"+provinceString.provinces);var s = "<option>-請選擇省份-</option>";for(var i=0;i<pro.length;i++){s += "<option>"+pro[i]+"</option>";}document.getElementById("province").innerHTML = s;//alert(xhr.responseText);}}}}function loadCitys(){xhr = createXMLHttpRequest();xhr.open("post","loadcitys.action",true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//alert(document.getElementById("province").value);xhr.send("province="+document.getElementById("province").value);xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200 || xhr.status == 304){var cityString = eval("("+xhr.responseText+")");var city = cityString.citys;var s = "<option>-請選擇城市-</option>";for(var i=0;i<city.length;i++){s += "<option>"+city[i]+"</option>";}document.getElementById("city").innerHTML = s;}}}}window.onload =  loadProvinces();function showInfo(){var info = "您所選擇的省份是:<h3>"+document.getElementById("province").value+"</h3>   選擇的城市是:<h3>"+document.getElementById("city").value+"</h3>";//alert(info);document.getElementById("info").innerHTML = info;}</script></head><body>請選擇省份:<select id="province" onchange="loadCitys(this.value)"></select>請選擇城市:<select id="city" onchange="showInfo()"></select><div id="info"></div><s:debug></s:debug></body></html>


好了,大功告成咯,仔細研磨研磨。 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.