版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、ajax 编程实践之与服务器通信AJAX 编程实践之与服务器通信首先看下看下相对简单些的- 向服务器发送一个包含有名/值对的简单查询串,在这种情况下XHP即可以用GET也可以用POST 。GETfunction doRequestUsingGET() createXMLHttpRequest();var queryString = GetAndPostExample? ;queryString = queryString + createQueryString()+ &timeStamp= + new Date().getTime();xmlHttp.onreadystatechange =
2、handleStateChange;xmlHttp.open( GET , queryString, true );xmlHttp.send( null );POSTfunction doRequestUsingPOST() createXMLHttpRequest();var url = GetAndPostExample?timeStamp= + new Date().getTime(); var queryString = createQueryString();xmlHttp.open( POST , url, true );xmlHttp.onreadystatechange = h
3、andleStateChange;xmlHttp.setRequestHeader( Content-Type , application/x-www-form-urlencoded );xmlHttp.send(queryString);queryString方法是用 POSTContent-Type就是名 /值对的参数形式了(如name=LiLin&age=23),在调用 OPEN 方法中,当请求的时候为了确保服务器知道请求体中有请求参数,需要调用setRequestHeader,将值设置为application/x-www-form-urlencoded.当然也可不放在请求体中(那就不要
4、用POST啦!)此时server处理:import java.io. * ;import . * ;import javax.servlet. * ;import javax.servlet.http. * ;public class GetAndPostExample extends HttpServlet protected void processRequest(HttpServletRequest request, HttpServletResponse response, String method)throws ServletException, IOExcepti
5、on / Set content type of the response to text/xml response.setContentType( text/xml );/ Get the users inputString firstName = request.getParameter( firstName );String middleName = request.getParameter( middleName );String birthday = request.getParameter( birthday );/ Create the response textString r
6、esponseText = Hello + firstName + + middleName+ . Your birthday is + birthday + . + Method: + method + ;/ Write the response back to the browser PrintWriter out = response.getWriter(); out.println(responseText);/ Close the writerout.close();protected void doGet(HttpServletRequest request, HttpServle
7、tResponse response)throws ServletException, IOException / Process the request in method processRequest processRequest(request, response, GET );protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException / Process the request in method processRe
8、quest processRequest(request, response, POST );对 get and post方法都用processRequest来处理。要向服务器发送相关复杂的查询串,可以将模型变化为XML 发送到 server。client端 :function createXML() var xml = ;var options = document.getElementById( petTypes ).childNodes;var option = null ;for ( var i = 0 ; i options.length; i + ) option = option
9、si;if (option.selected) xml = xml + + option.value + ;xml = xml + ;return xml;function sendPetTypes() createXMLHttpRequest();var xml = createXML();var url = PostingXMLExample?timeStamp= + new Date().getTime();xmlHttp.open( POST , url, true );xmlHttp.onreadystatechange = handleStateChange;xmlHttp.set
10、RequestHeader( Content-Type , application/x-www-form-urlencoded );xmlHttp.send(xml);createXML方法无非就是将内容以DOM的样式存到var xml(变量)里。有时也可能出现client直接将本地的一个XML文件直接以DOM (当然可以edit )的样式传送.(也放这个时个的Content-Type应该为text/xml了 !) 这时可能要用到ActiveXObject(MSXML2.DOMDocument.3.0)这样一个控件了。关于这个控件有个方法可以在各broswer中通用的JS 代码:/ -/ Fu
11、nction: CreateXMLDOM/ Purpose: Creates a new XML DOM./ Parameters: None/ Returns: XMLDOM object OR null/ -function CreateXmlDOM()var oXML = new ActiveXObject(GetXmlParserProgID();tryoXML.setProperty( AllowXsltScript , true );catch (err) oXML.async = false ;oXML.validateOnParse = false ;oXML.resolveE
12、xternals = false ;oXML.setProperty( SelectionLanguage , XPath );try oXML.setProperty( NewParser , true ); catch (e) return oXML;/ -/ Function: GetXmlParserProgID/ Purpose:/ Gets the ProgID of the highest available version of the/ Microsoft XML parser./ Parameters: None/ Returns: String (i.e. Msxml2.
13、DOMDocument.4.0)/ -function GetXmlParserProgID()var MAX_MAJOR_PARSER_VERSION = 10 ;var MIN_MAJOR_PARSER_VERSION = 0 ;var MAX_MINOR_PARSER_VERSION = 9 ;var MIN_MINOR_PARSER_VERSION = 0 ;var sProgID = g_sXmlParserProgID;var bFound = false ;if ( ! sProgID)/ Iterate through possible versionsfor ( var nM
14、ajor = MAX_MAJOR_PARSER_VERSION; nMajor =MIN_MAJOR_PARSER_VERSION; nMajor - )for ( var nMinor = MAX_MINOR_PARSER_VERSION; nMinor = MIN_MINOR_PARSER_VERSION; nMinor - )/ Set up the classname for the version that were trying to instantiate sProgID = Msxml2.DOMDocument. + nMajor + . + nMinor;tryif ( ne
15、w ActiveXObject(sProgID)bFound = true ;break ;catch (e)if (bFound)/ store in a global variable to speedup subsequent calls g_sXmlParserProgID = sProgID;break ;return sProgID;然后直接用其load方法(本地)。var xmlDoc = new ActiveXObject( MSXML2.DOMDocument.3.0 );xmlDoc.load(local_XML_FileName);当然也可以直接从server取来(用ge
16、t 方法即可),然后以responseText的方法xmlht.Open( GET ,server_XML_FileName, true );xmlht.onreadystatechange = stateChange;xmlht.Send( null );function handleStateChange() if (xmlHttp.readyState = 4 ) if (xmlHttp.status = 200 ) xmlDoc.loadXML(xmlht.responseText);实际上 xmlDoc.loadXML(xmlht.responseText)所得到的就是一个于内存中的
17、DOM 了,而直接用responseXML的话就直接可以解析为一个DOM 了 !(注意 load ( FILE )与 loadXML (DOM )是不同的 )此时 servert process :import java.io. * ;import javax.servlet. * ;import javax.servlet.http. * ;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Docume
18、nt;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class PostingXMLExample extends HttpServlet protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException String xml = readXMLFromRequestBody(request);Document xmlDoc = null ;t
19、ry xmlDoc =DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new ByteArrayInputStream(xml.getBytes();catch (ParserConfigurationException e) System.out.println( ParserConfigurationException: + e);catch (SAXException e) System.out.println( SAXException: + e);/*/ /* Note how the Java implementation of the W3C DOM has the same methods* as the JavaScript implementation, such as getElementsByTagName and* getNodeValue.*/NodeList selectedPetTypes = xmlDoc.getElementsByTa
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
评论
0/150
提交评论