您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 销售管理 > ajax编程实践之与服务器通信
AJAX编程实践之与服务器通信首先看下看下相对简单些的--向服务器发送一个包含有名/值对的简单查询串,在这种情况下XHP即可以用GET也可以用POST。GETfunctiondoRequestUsingGET(){createXMLHttpRequest();varqueryString=GetAndPostExample?;queryString=queryString+createQueryString()+&timeStamp=+newDate().getTime();xmlHttp.onreadystatechange=handleStateChange;xmlHttp.open(GET,queryString,true);xmlHttp.send(null);}POSTfunctiondoRequestUsingPOST(){createXMLHttpRequest();varurl=GetAndPostExample?timeStamp=+newDate().getTime();varqueryString=createQueryString();xmlHttp.open(POST,url,true);xmlHttp.onreadystatechange=handleStateChange;xmlHttp.setRequestHeader(Content-Type,application/x-);xmlHttp.send(queryString);}queryString就是名/值对的参数形式了(如name=LiLin&age=23),在调用OPEN方法中,当请求方法是用POST的时候为了确保服务器知道请求体中有请求参数,需要调用setRequestHeader,将Content-Type值设置为application/x-当然也可不放在请求体中(那就不要用POST啦!)此时server处理:importjava.io.*;importjava.net.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassGetAndPostExampleextendsHttpServlet{protectedvoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse,Stringmethod)throwsServletException,IOException{//Setcontenttypeoftheresponsetotext/xmlresponse.setContentType(text/xml);//Gettheuser'sinputStringfirstName=request.getParameter(firstName);StringmiddleName=request.getParameter(middleName);Stringbirthday=request.getParameter(birthday);//CreatetheresponsetextStringresponseText=Hello+firstName++middleName+.Yourbirthdayis+birthday+.+[Method:+method+];//WritetheresponsebacktothebrowserPrintWriterout=response.getWriter();out.println(responseText);//Closethewriterout.close();}protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{//ProcesstherequestinmethodprocessRequestprocessRequest(request,response,GET);}protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{//ProcesstherequestinmethodprocessRequestprocessRequest(request,response,POST);}}对getandpost方法都用processRequest来处理。要向服务器发送相关复杂的查询串,可以将模型变化为XML发送到server。client端:functioncreateXML(){varxml=pets;varoptions=document.getElementById(petTypes).childNodes;varoption=null;for(vari=0;ioptions.length;i++){option=options[i];if(option.selected){xml=xml+type+option.value+\/type;}}xml=xml+\/pets;returnxml;}functionsendPetTypes(){createXMLHttpRequest();varxml=createXML();varurl=PostingXMLExample?timeStamp=+newDate().getTime();xmlHttp.open(POST,url,true);xmlHttp.onreadystatechange=handleStateChange;xmlHttp.setRequestHeader(Content-Type,application/x-);xmlHttp.send(xml);}createXML方法无非就是将内容以DOM的样式存到varxml(变量)里。有时也可能出现client直接将本地的一个XML文件直接以DOM(当然可以edit)的样式传送.(也放这个时个的Content-Type应该为text/xml了!)这时可能要用到ActiveXObject(MSXML2.DOMDocument.3.0)这样一个控件了。关于这个控件有个方法可以在各broswer中通用的JS代码://--------------------------------------------------------------------//Function:CreateXMLDOM////Purpose:CreatesanewXMLDOM.////Parameters:None////Returns:XMLDOMobjectORnull//--------------------------------------------------------------------functionCreateXmlDOM(){varoXML=newActiveXObject(GetXmlParserProgID());try{oXML.setProperty(AllowXsltScript,true);}catch(err){}oXML.async=false;oXML.validateOnParse=false;oXML.resolveExternals=false;oXML.setProperty(SelectionLanguage,XPath);try{oXML.setProperty(NewParser,true);}catch(e){}returnoXML;}//--------------------------------------------------------------------//Function:GetXmlParserProgID////Purpose://GetstheProgIDofthehighestavailableversionofthe//MicrosoftXMLparser.////Parameters:None////Returns:String(i.e.Msxml2.DOMDocument.4.0)////--------------------------------------------------------------------functionGetXmlParserProgID(){varMAX_MAJOR_PARSER_VERSION=10;varMIN_MAJOR_PARSER_VERSION=0;varMAX_MINOR_PARSER_VERSION=9;varMIN_MINOR_PARSER_VERSION=0;varsProgID=g_sXmlParserProgID;varbFound=false;if(!sProgID){//Iteratethroughpossibleversionsfor(varnMajor=MAX_MAJOR_PARSER_VERSION;nMajor=MIN_MAJOR_PARSER_VERSION;nMajor--){for(varnMinor=MAX_MINOR_PARSER_VERSION;nMinor=MIN_MINOR_PARSER_VERSION;nMinor--){//Setuptheclassnamefortheversionthatwe'retryingtoinstantiatesProgID=Msxml2.DOMDocument.+nMajor+.+nMinor;try{if(newActiveXObject(sProgID)){bFound=true;break;}}catch(e){}}if(bFound){//storeinaglobalvariabletospeedupsubsequentcallsg_sXmlParserProgID=sProgID;break;}}}returnsProgID;}然后直接用其load方法(本地)。varxmlDoc=newActiveXObject(MSXML2.DOMDocument.3.0);xmlDoc.load(local_XML_FileName);当然也可以直接从server取来(用get方法即可),然后以responseText的方法xmlht.Open(GET,server_XML_FileName,true);xmlht.onreadystatechange=stateChange;xmlht.Send(null);functionhandleStateChange(){if(xmlHttp.readyState==4){if(xmlHttp.status==200){xmlDoc.loadXML(xmlht.responseText);}}}实际上xmlDoc.loadXML(xmlht.responseText)所得到的就是一个于内存中的DOM了,而直接用responseXML的话就直接可以解析为一个DOM了!(注意load(FILE)与loadXML(DOM)是不同的)此时servertprocess:importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.ParserConfigurationException;importorg.w3c.dom.Docume
本文标题:ajax编程实践之与服务器通信
链接地址:https://www.777doc.com/doc-1577779 .html