icai项目开发日记(三)

四.struts中Ajax 的简单应用

  Ajax 现在已经热火朝天了,正好做这个小项目时有个功能最理想的方法就是用Ajax时,因为没学过javascript,费了好大的劲,也请教了不少人才弄明天下面这段代码是怎么回事.功能是实现了,不过对Ajax的实在了解不多,有空了以后好好再琢磨.不懂javascript.不会Ajax.struts中Ajax的简单应用.可以完全不用理会javascript.现在就来看看它的入门级用法.看看我是怎么实现的.

用到的Ajax代码如下:(可以不用知道是怎么回事,不过介意看完整个代码)

/**
 * Ajax.js
 *
 * Collection of Scripts to allow in page communication from browser to (struts) server
 * ie can reload part instead of full page
 *
 * How to use
 * ==========
 * 1) Call retrieveURL from the relevant event on the HTML page (e.g. onclick)
 * 2) Pass the url to contact (e.g. Struts Action) and the name of the HTML form to post
 * 3) When the server responds ...
 *         - the script loops through the response , looking for <span id="name">newContent</span>
 *          - each <span> tag in the *existing* document will be replaced with newContent
 *
 * NOTE: <span id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote
 *         Everything after the first '>' mark until </span> is considered content.
 *         Empty Sections should be in the format <span id="name"></span>
 
*/


// global variables
   var  req;
  
var  which;


  
/**
   * Get the contents of the URL via an Ajax call
   * url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1) 
   * nodeToOverWrite - when callback is made
   * nameOfFormToPost - which form values will be posted up to the server as part 
   *                    of the request (can be null)
   
*/

  
function  retrieveURL(url,nameOfFormToPost)  {
    
    
//get the (form based) params to push up as part of the get request
    url=url+getFormAsString(nameOfFormToPost);
    
    
//Do the Ajax call
    if (window.XMLHttpRequest) // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange 
= processStateChange;
      
try {
          req.open(
"GET", url, true); //was get
      }
 catch (e) {
        alert(
"Problem Communicating with Server "+e);
      }

      req.send(
null);
    }
 else if (window.ActiveXObject) // IE
      
      req 
= new ActiveXObject("Microsoft.XMLHTTP");
      
if (req) {
        req.onreadystatechange 
= processStateChange;
        req.open(
"GET", url, true);
        req.send();
      }

    }

  }


/*
   * Set as the callback method for when XmlHttpRequest State Changes 
   * used by retrieveUrl
  
*/

  
function  processStateChange()  {
  
        
if (req.readyState == 4// Complete
      if (req.status == 200// OK response
        
        
//alert("Ajax response:"+req.responseText);
        
        
//Split the text response into Span elements
        spanElements = splitTextIntoSpan(req.responseText);
        
        
//Use these span elements to update the page
        replaceExistingWithNewHtml(spanElements);
        
      }
 else {
          alert(
"Ajax response:"+req.responseText);
        
//alert("Problem with server response:  " + req.statusText);
      }

    }

  }

 
 
/**
  * gets the contents of the form as a URL encoded String
  * suitable for appending to a url
  * @param formName to encode
  * @return string with encoded form values , beings with &
  
*/
 
 
function  getFormAsString(formName) {
     
     
//Setup the return String
     returnString ="";
     
      
//Get the form values
     formElements=document.forms[formName].elements;
     
     
//loop through the array , building up the url
     //in the form /strutsaction.do&name=value
     
     
for ( var i=formElements.length-1; i>=0--i ){
         
//we escape (encode) each value
         returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
     }

     
     
//return the values
     return returnString; 
 }

 
 
/**
 * Splits the text into <span> elements
 * @param the text to be parsed
 * @return array of <span> elements - this array can contain nulls
 
*/

 
function  splitTextIntoSpan(textToSplit) {
 
      
//Split the document
     returnElements=textToSplit.split("</span>")
     
     
//Process each of the elements     
     for ( var i=returnElements.length-1; i>=0--i ){
         
         
//Remove everything before the 1st span
         spanPos = returnElements[i].indexOf("<span");        
         
         
//if we find a match , take out everything before the span
         if(spanPos>0){
             subString
=returnElements[i].substring(spanPos);
             returnElements[i]
=subString;
         
         }
 
     }

     
     
return returnElements;
 }

 
 
/*
  * Replace html elements in the existing (ie viewable document)
  * with new elements (from the ajax requested document)
  * WHERE they have the same name AND are <span> elements
  * @param newTextElements (output of splitTextIntoSpan)
  *                    in the format <span id=name>texttoupdate
  
*/

 
function  replaceExistingWithNewHtml(newTextElements) {
 
     
//loop through newTextElements
     for ( var i=newTextElements.length-1; i>=0--i ){
  
         
//check that this begins with <span
         if(newTextElements[i].indexOf("<span")>-1){
             
             
//get the name - between the 1st and 2nd quote mark
             startNamePos=newTextElements[i].indexOf('"')+1;
             endNamePos
=newTextElements[i].indexOf('"',startNamePos);
             name
=newTextElements[i].substring(startNamePos,endNamePos);
             
             
//get the content - everything after the first > mark
             startContentPos=newTextElements[i].indexOf('>')+1;
             content
=newTextElements[i].substring(startContentPos);
             
             
//Now update the existing Document with this element
             
                 
//check that this element exists in the document
                 if(document.getElementById(name)){
                 
                     
//alert("Replacing Element:"+name);
                     document.getElementById(name).innerHTML = content;
                 }
 else {
                     alert(
"Element:"+name+"not found in existing document");
                 }

         }

     }

 }

视图层的jsp页面如下:(仅贴出使用相关的代码)

 

<% @page contentType="text/html;charset=gb2312" language="java" isELIgnored="false" %>
< html:form  action ="/lr0Analyze"  method ="POST"    >
< align ="left" >
选择文法:
  
< html:select  property ="select_grammar"  onchange ="retrieveURL('grammarAjax.do?tableName=GRAMMAR','lr0AnalyzeForm');" >
     
< html:options  collection ="grammarCollection"  property ="label"  labelProperty ="label" />
  
</ html:select >
</ P >
  
< align ="left" >
  输入文法:                                                                      
  
<!--  1.Default Return Blank  -->   
  
< logic:notPresent  name ="SELECTED_GRAMMAR"  scope ="request" >
  
< span  id ="thegrammar" >                                        
    
< html:textarea  property ="selected_grammar"  rows ="7"  cols ="40" >
    
</ html:textarea > *
  
</ span >
  
</ logic:notPresent >
  
<!--  2.Return content if requested -->     
  
< logic:present  name ="SELECTED_GRAMMAR"  scope ="request" >
    
< span  id ="thegrammar" >          
      
< html:textarea  property ="selected_grammar"  rows ="7"  cols ="40"  value ="${SELECTED_GRAMMAR}" >
      
</ html:textarea > *     
    
</ span >       
  
</ logic:present >                                            
  
</ P >
  
< align ="left" >
  输 入 串  :
  
< html:text  maxlength ="40"  property ="input_lr0"  size ="40" /> 必须以 < FONT  color ="#ff0000" > </ FONT > 号结尾
</ P >
  
< align ="left" >
  
< html:submit />< html:reset />
</ P >
</ html:form >

  如代码所示:代码中有两个<span id="thegrammar"> (thegrammar是保存在request域内的一个参数)两个代码表示的意思分别是:1.当request域内不存在thegrammar时使用期1。2.当request域内存在thegrammar时使用期2。form提交的目标是grammarAjax.do.(struts-config.xml中定义的名字)

< html:textarea  property ="selected_grammar"  rows ="7"  cols ="40"  value ="${SELECTED_GRAMMAR}" >

将<html:textarea>的值设为${SELECTED_GRAMMAR};

Ajax可以接收任一后台处理的结果。jsp,servlet,action等。要做的只要将处理结果保存到相应的区域(request,reponse,application)使用action处理如下(此即为grammarAjax.do 对应的代码):

package  ysu.cs.icai.action;
import  javax.servlet.ServletContext;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;

import  org.apache.struts.action.Action;
import  org.apache.struts.action.ActionForm;
import  org.apache.struts.action.ActionForward;
import  org.apache.struts.action.ActionMapping;

import  java.sql. * ;
import  ysu.cs.icai.common. * ;
import  ysu.cs.icai.database.ConDatabase;

/** 
 * MyEclipse Struts
 * Creation date: 08-30-2006
 * 
 * XDoclet definition:
 * @struts.action validate="true"
 
*/

public   class  GrammarAjaxAction  extends  Action  {
    
/** 
     * Method execute
     * 
@param mapping
     * 
@param form
     * 
@param request
     * 
@param response
     * 
@return ActionForward
     
*/

    
public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response) 
{
        
        ConDatabase dataSource;
        java.sql.Connection myConnection;
        Statement st;
        ResultSet set;
        String sel
=request.getParameter("select_grammar");
        String labeltable
=request.getParameter("tableName");
        String sql
="select * from "+labeltable+" where label='"+sel+"'";//the value of "tableName" is GRAMMAR OR FORMULA 
        
        
try{
            ServletContext application
=request.getSession().getServletContext();
            
            dataSource
=(ConDatabase)application.getAttribute("DATASOURCE");
            myConnection
=dataSource.getConnection();

            st
=myConnection.createStatement();
            st.execute(
"use icaidb;");
            set
=st.executeQuery(sql);
            
while(set.next()){
                String re
=set.getString(2);
                re
=Common.removeTransferredMeaning(re);
                //System.out.print(re);
                request.setAttribute(
"SELECTED_GRAMMAR",re);        
                
//System.out.print(re);
            }

        }
catch(SQLException er){
            er.printStackTrace();
        }

        
return mapping.findForward("SUCCESS_PATH");
    }

}


这段代码相信大家都看能看明白:根据select_grammar和tablename这两个属性在一个数据库中检索相应的数据后,并将结果返回.(注意相保存在到request,reponse,application...任一作用域中).

 可以参考如下文章(以下列表摘自www.ibm.com):

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值