一个ajax学习示例

本文介绍了一个使用Ajax技术实现的动态加载内容的例子。通过选择不同的选项,页面会异步请求服务器并更新显示区域,展示了科技成果、中试机构及专家数量等不同内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.示例说明:

  根据用户选择下拉列表值的不同,页面的局部区域显示不同的效果.显示效果如下图:

 

首页选择列表

选择科技成果,出现table.

选择中试机构,出现相应文件;

选择专家数量,出现文字

注意:根据用户的选择项而相应地显示不同的内容,这个内容的设置见CategoryServlet.java中htmlStr.

二.源码显示:

1.工程文件结构表

2.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>
    
<description>This is the description of my J2EE component</description>
    
<display-name>This is the display name of my J2EE component</display-name>
    
<servlet-name>CategoryServlet</servlet-name>
    
<servlet-class>com.servlet.CategoryServlet</servlet-class>
  
</servlet>
  
<servlet>
    
<description>This is the description of my J2EE component</description>
    
<display-name>This is the display name of my J2EE component</display-name>
    
<servlet-name>SysInitServlet</servlet-name>
    
<servlet-class>com.servlet.SysInitServlet</servlet-class>
    
<init-param>
        
<param-name>webapp-root</param-name>
        
<param-value>/jsp</param-value>
    
</init-param>
    
<load-on-startup>1</load-on-startup>
  
</servlet>

  
<servlet-mapping>
    
<servlet-name>CategoryServlet</servlet-name>
    
<url-pattern>/servlet/CategoryServlet</url-pattern>
  
</servlet-mapping>
  
<servlet-mapping>
    
<servlet-name>SysInitServlet</servlet-name>
    
<url-pattern>/servlet/SysInitServlet</url-pattern>
  
</servlet-mapping>
</web-app>

注意:关于SysInitServlet的说明如下:

  A.如果jsp页面较少,SysInitServlet可以不用设置.

  B.如果jsp页面较多,根据实现功能被包含在不同的页面中,那么就可以通过设置init-param,来进行设置.这样做能清楚地找到页面所在的文件夹,避免在相应页面进行图片等的链接时,出现找不到的错误.

2.SysInitServlet.java中的部分代码如下:

    public void init() throws ServletException {
            
// Put your code here
        String webapp_root = this.getInitParameter("webapp-root");
        
this.getServletContext().setAttribute("webapp-root", webapp_root);
    }

其中,doGet()与doPost()为空即可;

3.CategoryServlet.java中的主要代码如下:

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {
        
        String responseStr 
= "";
        String htmlStr 
= "";
        String category 
= request.getParameter("category");
        System.out.print(category);
        
if((category != null&& category.equals("achs")){
            htmlStr 
= " <table width='200' border='1' cellpadding='0' cellspacing='0' bgcolor='#99FF33'> <tr><td>you selected the first.</td></tr><tr><td>an example for using ajax! </td></tr></table>";
        }
 else if((category != null&& category.equals("orgs")) {
            htmlStr 
= "how delighted to use the ajax!<br>You select <font color='#ff0000'>organizations!</font>";
        }
 else if((category != null&& category.equals("exps")) {
            htmlStr 
= "You have selected the Third!<br>You select <font color='#ff0000'>experts!</font>";
        }
 else 
            htmlStr 
= "";
        System.out.println(htmlStr);
        responseStr 
= "<?xml version="1.0" encoding="UTF-8"?><root><content><![CDATA[ "+htmlStr+" ]]></content></root>";
        System.out.println(responseStr);
        response.setContentType(
"text/xml;charset=UTF-8");
        PrintWriter writer 
= response.getWriter();
        writer.print(responseStr);
        writer.flush();
        writer.close();
    }

4.testcommon.js中的代码如下:

function selectCategory(category, action){
//    alert("You select: "+category);
    TestMap_Action_Category(category,action);
}


function TestMap_Action_Category(category, action){
    
var string = "category="+category;
    
//alert(string);
    TestMap_Action_Post(action,string,TestMap_Action_Category_Response);
}


function TestMap_Action_Post(url,query,handler){
    
var status = false;
    
var contentType = "application/x-www-form-urlencoded; charset=UTF-8";
    
// Native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        request 
= new XMLHttpRequest();
        request.onreadystatechange 
= handler;
        request.open(
"post", url, true);
        request.setRequestHeader(
"Content-Type", contentType);
        request.send(query);
        status 
= true;

    
// ActiveX XMLHttpRequest object
    }
 else if (window.ActiveXObject) {
        request 
= new ActiveXObject("Microsoft.XMLHTTP");
        
if (request) {
            request.onreadystatechange 
= handler;
            request.open(
"post", url, true);
            request.setRequestHeader(
"Content-Type", contentType);
            request.send(query);
            status 
= true;
        }

    }

    
return status;
}


function  TestMap_Action_Category_Response(){
    
if(request.readyState == 4{
        
if(request.status == 200{
            
var responseDom = request.responseXML.documentElement;
            
var mapData = responseDom.getElementsByTagName('content')[0].firstChild.data;
//            it's better to add the sentence to test the HTML returned;
//
            alert(mapData);
            document.getElementById('showMap').innerHTML = mapData;
        }
 else {
            alert(
'There was a problem the request');
        }

    }

}

5.index.jsp如下:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String appRoot = path + application.getAttribute("webapp-root");
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  
<head>
    
<base href="<%=basePath%>">
    
    
<title>a little example for using 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" href="styles.css">
    
-->
    
<script type="text/javascript" src="<%=path%>/common-js/testcommon.js" ></script>
    
<%
        
String action_SC = path + "/servlet/CategoryServlet";
        System.out.println(action_SC);
     
%>
  
</head>
  
  
<body>

     
<form name="form"">
        
<select name="categorys" >
                
<option value="ples" selected="selected">请选择</option>
                
<option value="achs">科技成果</option>
                
<option value="orgs">中试机构</option>
                
<option value="exps">专家数量</option>
        
</select><br>
        
<input type="button" value="OK"   onclick="selectCategory(this.form.categorys.value,'<%=action_SC%>')">
        
<input type="reset" value="cancel">
        
<div id="showMap"></div>
    
</form>
  
</body>
</html>

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值