icai项目开发日记(三)
来源:互联网 发布:德国 知乎 编辑:程序博客网 时间:2024/06/05 05:37
四.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页面如下:(仅贴出使用相关的代码)
<html:form action="/lr0Analyze" method="POST" >
<P 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>
<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>
<P align="left">
输 入 串 :
<html:text maxlength="40" property="input_lr0" size="40"/>必须以<FONT color="#ff0000">#</FONT>号结尾
</P>
<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>的值设为${SELECTED_GRAMMAR};
Ajax可以接收任一后台处理的结果。jsp,servlet,action等。要做的只要将处理结果保存到相应的区域(request,reponse,application)使用action处理如下(此即为grammarAjax.do 对应的代码):
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):
XMLHttpRequest
对象,请阅读 关于 XMLHttpRequest
对象的这篇文章。 - icai项目开发日记(三)
- icai项目开发日记(-)
- icai项目开发日记(二)
- SOLOT开发日记(三)
- MyEyes项目开发日记之三(添加新浪微博功能)
- 饕餮元年开发日记(三)
- android WIFI DRIVER 开发日记(三)
- android WIFI DRIVER 开发日记(三)
- android WIFI DRIVER 开发日记(三)
- 点点细雨的项目日记(三) 三…
- 项目开发实训日记(二)
- 项目开发成长日记
- avr开发板开发项目日记(一)
- ASP.NET项目开发日记
- MyEyes项目开发日记之一
- Qt项目开发日记1
- android wifi驱动开发日记(二)(三)
- zxing项目开发(三)
- 春笛短信模块的使用说明
- 浅谈Java的输入输出编码
- java测试代码
- 一个qreport的例子:中文多行显示,表格线在多行显示时的扩展,扩展之后的手动分页,文本式的反向报表(试过)
- 国庆值班第一天
- icai项目开发日记(三)
- .NET下基于API封装的DirectUIHWND窗体访问
- .NET中Form之间的互相调用
- .NET中获取电脑名、IP及用户名方法
- 误导程序员的喧嚣:评CSDN引导Java和Ruby之争
- Windows平台下PHP5.0+Mysql4.1.x环境架设(1-6)[转]
- Windows平台下PHP5.0+Mysql4.1.x环境架设(2)
- Ubuntu HOWTO: 3D Acceleration in ATI Mobility Radeon M6 LY (and possibly others)
- Windows平台下PHP5.0+Mysql4.1.x环境架设(3)