All articles| All Pictures| All Softwares| All Video| Go home page| Write articles| Upload pictures

Reading number is top 10 articles
警告!Ajax技术的安全问题不容忽视_.net资料_编程技术
sql server日志文件总结及日志满的处理办法_[SQL Server教程]
VS2005下水晶报表如何实现动态数据源绑定-_[Asp.Net教程]
PHP应用:PHP在linxu下的安装与配置_[PHP教程]
PHP的print函数_[PHP教程]
Community,Server专题一:概述Community,Server_[Asp.Net教程]
C#的Windows编程中多语言的实现_.net资料_编程技术
ASP.NET从零起步设计网站全过程(5)_[Asp.Net教程]
Asp.net,MVC2.0初级教程-添加操作_[Asp.Net教程]
缓存技术详谈—php_[PHP教程]
Reading number is top 10 pictures
Sexy women in 2013--1
白嫩丰满美女照片
邪恶搞笑内涵图
移民小国也实惠1
XuRe xuan cool and refreshing photoes1
为什么别人说你是疯子
9.3阅兵全景图3-外国方阵梯队和坦克方阵梯队
每天进步一点点
The Soviet union swimsuit exposure in the 70 year3
The real super beauty12
Download software ranking
Sora aoi's film--cangkong_Blue.Sky
Such love down(擒爱记)
美女写真3
Tram sex maniac 2 (H) rar bag10
实战黑客不求人
The Bermuda triangle1
I for your crazy
WebService在.NET中的实战应用教学视频 → 第1集
Tram sex maniac 2 (H) rar bag9
仙剑奇侠传98版歌曲
归海一刀 published in(发表于) 2014/3/16 2:53:00 Edit(编辑)
AJAX编程实践之与服务器通信_[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);
}

  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 " );
 }
}

  对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 = options[i];
  if (option.selected) {
   xml = xml + " " + 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;
}


  然后直接用其load方法(本地)。


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);
  }
 }
}

  实际上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();
}
}

  DOM,JDOM,JAXP随便你自己选好了!
作者:Jkallen 来源:BLOGCHINA





添加到del.icio.us 添加到新浪ViVi 添加到百度搜藏 添加到POCO网摘 添加到天天网摘365Key 添加到和讯网摘 添加到天极网摘 添加到黑米书签 添加到QQ书签 添加到雅虎收藏 添加到奇客发现 diigo it 添加到饭否 添加到飞豆订阅 添加到抓虾收藏 添加到鲜果订阅 digg it 貼到funP 添加到有道阅读 Live Favorites 添加到Newsvine 打印本页 用Email发送本页 在Facebook上分享


Disclaimer Privacy Policy About us Site Map

If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.