Ajax Programming Practice Server communication

Source: Internet
Author: User
Tags date query string version variable tostring xml parser stringbuffer
First look at the relatively simple-send a simple query string that contains a well-known/value pair to the server, in which case XHP can use Get or 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 is the Parameter form of a name/value pair (such as name=lilin&age=23), in the call to the open method, when the request method is post, in order to ensure that the server knows the request parameters in the request body. You need to call setRequestHeader and set the Content-type value to application/x-www-form-urlencoded. It's also not in the request body (don't post it!). )

At this point the server handles:

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

Both the Get and post methods are treated with ProcessRequest.

To send a related complex query string to the server, you can send the model changes to the XML to the server.

Client side:

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

The Createxml method is simply to save the content in the style of Dom into the var XML (variable). It is also sometimes possible for a client to directly transfer a local XML file directly to the DOM (of course, edit). (also put this time the content-type should be for Text/xml!) ActiveXObject ("MSXML2") may be used at this time. domdocument.3.0 ") such a control.

There is a method for this control that can be used in each broswer of the JS code:

// --------------------------------------------------------------------
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 so 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;
}

Then use its Load method directly (local).

var xmldoc = new ActiveXObject ("MSXML2. domdocument.3.0 ");
Xmldoc.load (Local_xml_filename);

Of course, it can be taken directly from the server (using the Get method), and then the ResponseText method

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

In fact Xmldoc.loadxml (Xmlht.responsetext) is a DOM in memory, and directly with Responsexml can be resolved into a DOM! (Note that load (FILE) is different from Loadxml (DOM))

At this point 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);
}

/**//* How the Java implementation of the "the" the "the" has DOM 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, choose your own choice!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.