DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解 >> AJAX編程實踐服務器通信
AJAX編程實踐服務器通信
編輯:AJAX詳解     
首先看下看下相對簡單些的--向服務器發送一個包含有名/值對的簡單查詢串,在這種情況下XHP即可以用GET也可以用POST。
GET

function doRequestUsingGET() {
 createXMLHttpRequest();

 var queryString = " GetAndPostExample? " ;
 queryString = queryString + createQueryString()+ " &timeStamp= " + new Date().getTime();
 XMLHttp.onreadystatechange = handleStateChange;
 XMLHttp.open( " GET " , queryString, true );
 XMLHttp.send( null );
}

POST

function doRequestUsingPOST() {
 createXMLHttpRequest();

 var url = " GetAndPostExample?timeStamp= " + new Date().getTime();
 var queryString = createQueryString();

 XMLHttp.open( " POST " , url, true );
 XMLHttp.onreadystatechange = handleStateChange;
 XMLHttp.setRequestHeader( " Content-Type " , " application/x-www-form-urlencoded " );
 XMLHttp.send(queryString);
}
GET

function doRequestUsingGET() {
 createXMLHttpRequest();

 var queryString = " GetAndPostExample? " ;
 queryString = queryString + createQueryString()+ " &timeStamp= " + new Date().getTime();
 XMLHttp.onreadystatechange = handleStateChange;
 XMLHttp.open( " GET " , queryString, true );
 XMLHttp.send( null );
}

POST

function doRequestUsingPOST() {
 createXMLHttpRequest();

 var url = " GetAndPostExample?timeStamp= " + new Date().getTime();
 var queryString = createQueryString();

 XMLHttp.open( " POST " , url, true );
 XMLHttp.onreadystatechange = handleStateChange;
 XMLHttp.setRequestHeader( " Content-Type " , " application/x-www-form-urlencoded " );
 XMLHttp.send(queryString);
}
  queryString就是名/值對的參數形式了(如name=LiLin&age=23),在調用OPEN方法中,當請求方法是用POST的時候為了確保服務器知道請求體中有請求參數,需要調用setRequestHeader,將Content-Type值設置為application/x-www-form-urlencoded.當然也可不放在請求體中(那就不要用POST啦!)

  此時server處理:
import Java.io. * ;
import Java.Net. * ;
import Javax.servlet. * ;
import Javax.servlet.http. * ;

public class GetAndPostExample extends HttpServlet {

 protected void processRequest(HttpServletRequest request, HttpServletResponse response, String method)
throws ServletException, IOException {

  // Set content type of the response to text/XML
  response.setContentType( " text/XML " );

  // Get the user's input
  String firstName = request.getParameter( " firstName " );
  String middleName = request.getParameter( " middleName " );
  String birthday = request.getParameter( " birthday " );

  // Create the response text
  String responseText = " 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 writer
  out.close();
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse 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 processRequest
  processRequest(request, response, " POST " );
 }
}
import Java.io. * ;
import Java.Net. * ;
import Javax.servlet. * ;
import Javax.servlet.http. * ;

public class GetAndPostExample extends HttpServlet {

 protected void processRequest(HttpServletRequest request, HttpServletResponse response, String method)
throws ServletException, IOException {

  // Set content type of the response to text/XML
  response.setContentType( " text/XML " );

  // Get the user's input
  String firstName = request.getParameter( " firstName " );
  String middleName = request.getParameter( " middleName " );
  String birthday = request.getParameter( " birthday " );

  // Create the response text
  String responseText = " 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 writer
  out.close();
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse 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 processRequest
  processRequest(request, response, " POST " );
 }
}
  對get and post方法都用processRequest來處理。

  要向服務器發送相關復雜的查詢串,可以將模型變化為XML發送到server 。

  clIEnt端:
function createXML() {
 var XML = " <pets> " ;

 var options = document.getElementById( " petTypes " ).childNodes;
 var option = null ;
 for ( var i = 0 ; i < options.length; i ++ ) {
  option = options[i];
  if (option.selected) {
   xml = XML + " <type> " + option.value + " <\/type> " ;
  }
 }

 xml = XML + " <\/pets> " ;
 return XML;
}

function sendPetTypes() {
 createXMLHttpRequest();

 var xml = createXML();
 var url = " PostingXMLExample?timeStamp= " + new Date().getTime();

 XMLHttp.open( " POST " , url, true );
 XMLHttp.onreadystatechange = handleStateChange;
 XMLHttp.setRequestHeader( " Content-Type " , " application/x-www-form-urlencoded " );
 xmlHttp.send(XML);
}
function createXML() {
 var XML = " <pets> " ;

 var options = document.getElementById( " petTypes " ).childNodes;
 var option = null ;
 for ( var i = 0 ; i < options.length; i ++ ) {
  option = options[i];
  if (option.selected) {
   xml = XML + " <type> " + option.value + " <\/type> " ;
  }
 }

 xml = XML + " <\/pets> " ;
 return XML;
}

function sendPetTypes() {
 createXMLHttpRequest();

 var xml = createXML();
 var url = " PostingXMLExample?timeStamp= " + new Date().getTime();

 XMLHttp.open( " POST " , url, true );
 XMLHttp.onreadystatechange = handleStateChange;
 XMLHttp.setRequestHeader( " 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代碼:
// --------------------------------------------------------------------
// 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.async = false ;
 oXML.validateOnParse = false ;
 oXML.resolveExternals = 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.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 versions
  for ( var nMajor = 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 we're trying to instantiate
    sProgID = " MsXML2.DOMDocument. " + nMajor + " . " + nMinor;

    try
    {
     if ( new ActiveXObject(sProgID))
     {
      bFound = true ;
      break ;
     }
    }
    catch (e)
    {}
   }

   if (bFound)
   {
    // store in a global variable to speedup subsequent calls
    g_sXMLParserProgID = sProgID;
    break ;
   }
  }
 }

 return sProgID;
}

// --------------------------------------------------------------------
// 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.async = false ;
 oXML.validateOnParse = false ;
 oXML.resolveExternals = 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.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 versions
  for ( var nMajor = 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 we're trying to instantiate
    sProgID = " MsXML2.DOMDocument. " + nMajor + " . " + nMinor;

    try
    {
     if ( new 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);
var xmlDoc = new ActiveXObject( " 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 );

function handleStateChange() {
 if (XMLHttp.readyState == 4 ) {
  if (XMLHttp.status == 200 ) {
   xmlDoc.loadXML(XMLht.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();
}
}
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();
}
}
  DOM,JDOM,JAXP隨便你自己選好了!
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved