ajax|服务器 首先看下看下相对简单些的——向服务器发送一个包含有名/值对的简单查询串,在这种情况下XHP即可以用GET也可以用POST。 GET function doRequestUsingGET() { var queryString = " GetAndPostExample? " ; " &timeStamp= " + new Date().getTime(); POST function doRequestUsingPOST() { var url = " GetAndPostExample?timeStamp= " + new Date().getTime(); xmlHttp.open( " POST " , url, true ); " application/x-www-form-urlencoded " ); queryString就是名/值对的参数形式了(如name=LiLin&age=23),在调用OPEN方法中,当请求方法是用POST的时候为了确保服务器知道请求体中有请求参数,需要调用setRequestHeader,将Content-Type值设置为application/x-www-form-urlencoded.当然也可不放在请求体中(那就不要用POST啦!) 此时server处理: import java.io. * ; public class GetAndPostExample extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response, String method) // Set content type of the response to text/xml // Get the user's input // Create the response text // Write the response back to the browser // Close the writer protected void doGet(HttpServletRequest request, HttpServletResponse response) protected void doPost(HttpServletRequest request, HttpServletResponse response) 要向服务器发送相关复杂的查询串,可以将模型变化为XML发送到server 。 client端: function createXML() { var options = document.getElementById( " petTypes " ).childNodes; xml = xml + " <\/pets> " ; function sendPetTypes() { var xml = createXML(); xmlHttp.open( " POST " , url, true ); " application/x-www-form-urlencoded " ); 关于这个控件有个方法可以在各broswer中通用的JS代码: oXML.async = false ; return oXML; // ------------------------------------------------- var sProgID = g_sXmlParserProgID; if ( ! sProgID) nMajor >= MIN_MAJOR_PARSER_VERSION; nMajor -- ) nMinor >= MIN_MINOR_PARSER_VERSION; nMinor -- ) we're trying to instantiate try if (bFound) speedup subsequent calls return sProgID; var xmlDoc = new ActiveXObject( " MSXML2.DOMDocument.3.0 " ); 当然也可以直接从server取来(用get方法即可),然后以responseText的方法。 xmlht.Open( " GET " ,server_XML_FileName, true ); function handleStateChange() { 实际上xmlDoc.loadXML(xmlht.responseText)所得到的就是一个于内存中的DOM了,而直接用responseXML的话就直接可以解析为一个DOM了!(注意load(FILE)与loadXML(DOM)是不同的) 此时servert process : import java.io. * ; public class PostingXMLExample extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) String xml = readXMLFromRequestBody(request); /**/ /* Note how the Java implementation of the W3C DOM has the same methods response.setContentType( " text/xml " ); private String readXMLFromRequestBody(HttpServletRequest request) {【导读】本文介绍如何利用AJAX实现与服务器通信的功能,并给出代码及其比较。
createXMLHttpRequest();
queryString = queryString + createQueryString()+
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open( " GET " , queryString, true );
xmlHttp.send( null );
}
createXMLHttpRequest();
var queryString = createQueryString();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader( " Content-Type " ,
xmlHttp.send(queryString);
}
对get and post方法都用processRequest来处理。
import java.net. * ;
import javax.servlet. * ;
import javax.servlet.http. * ;
throws ServletException, IOException {
response.setContentType( " text/xml " );
String firstName = request.getParameter( " firstName " );
String middleName = request.getParameter( " middleName " );
String birthday = request.getParameter( " birthday " );
String responseText = " Hello " + firstName + " " + middleName
+ " . Your birthday is " + birthday + " . "
+ " [Method: " + method + " ] " ;
PrintWriter out = response.getWriter();
out.println(responseText);
out.close();
}
throws ServletException, IOException {
// Process the request in method processRequest
processRequest(request, response, " GET " );
}
throws ServletException, IOException {
// Process the request in method processRequest
processRequest(request, response, " POST " );
}
}
var xml = " <pets> " ;
var option = null ;
for ( var i = 0 ; i < options.length; i ++ ) {
option = options[i];
if (option.selected) {
xml = xml + " <type> " + option.value + " <\/type> " ;
}
}
return xml;
}
createXMLHttpRequest();
var url = " PostingXMLExample?timeStamp= " + new Date().getTime();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader( " Content-Type " ,
xmlHttp.send(xml);
} // ------------------------------------------------
// Function: CreateXMLDOM
//
// Purpose: Creates a new XML DOM.
//
// Parameters: None
//
// Returns: XMLDOM object OR null
// -------------------------------------------------
function CreateXmlDOM()
{
var oXML = new ActiveXObject(GetXmlParserProgID());
try
{
oXML.setProperty( " AllowXsltScript " , true );
}
catch (err) {}
oXML.validateOnParse = false ;
oXML.resolveExternals = false ;
oXML.setProperty( " SelectionLanguage " , " XPath " );
try {oXML.setProperty( " NewParser " , true );} catch (e) {}
}
// Function: GetXmlParserProgID
//
// Purpose:
// Gets the ProgID of the highest available version of the
// Microsoft XML parser.
//
// Parameters: None
//
// Returns: String (i.e. "Msxml2.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 bFound = false ;
{
// Iterate through possible versions
for ( var nMajor = MAX_MAJOR_PARSER_VERSION;
{
for ( var nMinor = MAX_MINOR_PARSER_VERSION;
{
// Set up the classname for the version that
sProgID = " Msxml2.DOMDocument. " + nMajor + " . " + nMinor;
{
if ( new ActiveXObject(sProgID))
{
bFound = true ;
break ;
}
}
catch (e)
{}
}
{
// store in a global variable to
g_sXmlParserProgID = sProgID;
break ;
}
}
}
}然后直接用其load方法(本地)。
xmlDoc.load(local_XML_FileName);
xmlht.onreadystatechange = stateChange;
xmlht.Send( null );
if (xmlHttp.readyState == 4 ) {
if (xmlHttp.status == 200 ) {
xmlDoc.loadXML(xmlht.responseText);
}
}
}
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;
throws ServletException, IOException {
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);
}
* 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.getWriter().print(responseText);
}
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();
}
}
AJAX实践之与服务器通信
80酷酷网 80kuku.com