龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > Javascript编程 >

AJAX实践之与服务器通信(1)(3)

时间:2013-03-06 14:58来源:未知 作者:admin 点击:
分享到:
当然也可以直接从server取来(用get方法即可),然后以responseText的方法。 xmlht.Open( " GET " ,server_XML_FileName, true ); xmlht.onreadystatechange = stateChange; xmlht.Send( nu
当然也可以直接从server取来(用get方法即可),然后以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)所得到的就是一个于内存中的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.Document;
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 ;
try {
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.getElementsByTagName( " type " );
String type = null ;
String responseText = " Selected Pets: " ;
for ( int i = 0 ; i < selectedPetTypes.getLength(); i ++ ) {
type = selectedPetTypes.item(i).getFirstChild().getNodeValue();
responseText = responseText + " " + type;
}

response.setContentType( " text/xml " );
response.getWriter().print(responseText);
}

private String readXMLFromRequestBody(HttpServletRequest request) {
StringBuffer xml = new StringBuffer();
String line = null ;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null ) {
xml.append(line);
}
}
catch (Exception e) {
System.out.println( " Error reading XML: " + e.toString());
}
return xml.toString();
}
}

(责任编辑:铭铭)
精彩图集

赞助商链接