Ajax data Transmission Way example detailed _ajax related

Source: Internet
Author: User

An example of this article describes the way AJAX data is transmitted. Share to everyone for your reference, specific as follows:

When sending and receiving information in an asynchronous application, it is common to choose Plain Text and XML as the data format (refer to the Ajax usage examples of jquery learning notes), and there is now a more popular way: JSON (JavaScript Object notation). OK, here are some examples of these three data formats in AJAX asynchronous applications.

One, plain text mode

1, Send/Receive data:

The code is cheap. See codes:
Testjs.js

This function is equivalent to Document.getelementbyid/document.all function $ (s) {if (document.getElementById) {return eval (' Document.gete Lementbyid ("' + S + '") ');}
else {return eval (' document.all. ' + s);}}
  Creates a XMLHttpRequest object to send an AJAX request function createxmlhttp () {var xmlHttp = false; var arrsignatures = ["MSXML2. xmlhttp.5.0 "," MSXML2. xmlhttp.4.0 "," MSXML2. xmlhttp.3.0 "," MSXML2.
  XMLHTTP "," Microsoft.XMLHTTP "];
      for (var i = 0; i < arrsignatures.length i++) {try {xmlHttp = new ActiveXObject (arrsignatures[i));
    return xmlHttp; ' Catch (oerror) {xmlHttp = false;//ignore}}//throw new Error (' MSXML ' not ' installed on your Syst 
  EM. ");
  if (!xmlhttp && typeof xmlhttprequest!= ' undefined ') {xmlHttp = new XMLHttpRequest ();
return xmlHttp;
var xmlreq = Createxmlhttp ();
  Send AJAX processing requests (here simply verify the validity of username and password, default correct input: Username and password are test) function Validatepwd (otxt) {var url = "/ajaxoperations.aspx"; Xmlreq.open ("Post", url, True);
  Xmlreq.setrequestheader ("Content-length", OTxt.value.length + $ ("txtUserName"). Value.length);
  Xmlreq.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
  Xmlreq.onreadystatechange = CallBack; Xmlreq.send ("action=chkpwd&userinfos=" + Escape (Otxt.value + "/" + $ ("txtUserName"). Value); Send text} function CallBack () {if (xmlreq.readystate = = 4) {if (Xmlreq.status =) {alert (xmlreq.respons EText);
    Receive text} else if (Xmlreq.status = 404) {alert ("requested URL is not found.");
    else if (xmlreq.status = = 403) {alert ("Access denied.");
  else alert ("status is" + Xmlreq.status);
 }
}

Several additional file source code:

Jstest.htm

 
 

Ajaxoperations.aspx

Copy Code code as follows:
<%@ Page language= "C #" autoeventwireup= true "codebehind=" AjaxOperations.aspx.cs "inherits=" Webtest2008.ajaxoperations "%>

AjaxOperations.aspx.cs

Using System;
Using System.Collections.Generic;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Namespace WebTest2008
{public
  partial class AjaxOperations:System.Web.UI.Page
  {
    protected void Page _load (object sender, EventArgs e)
    {
      if (!string). IsNullOrEmpty (request["action") && request["action"] = = "Chkpwd")
      {
        string responsetxt = " User name and password do not match! ";
        String tempstr = request["Userinfos"];
        /* Testing in the actual project can be retrieved on the database, and so on related operations, where the simplified * * *
        (Tempstr.split (new char[] {'}, stringsplitoptions.removeemptyentries) [0] = = "Test" && tempstr.split (new char[] {'}, stringsplitoptions.removeemptyentries) [1] = = "Test")
        {
   responsetxt = "Verify through!" ";
        }
        Response.Write (Responsetxt);}}}


One by one save the file, Ctrl+f5, run and try it.

The above method is the simplest, most direct and most effective way. Proficiency in the use of the best.

Second, the XML way

1. Send XML data

Testjs.js

This function is equivalent to Document.getelementbyid/document.all function $ (s) {if (document.getElementById) {return eval (' Document.gete Lementbyid ("' + S + '") ');}
else {return eval (' document.all. ' + s);}}
  Creates a XMLHttpRequest object to send an AJAX request function createxmlhttp () {var xmlHttp = false; var arrsignatures = ["MSXML2. xmlhttp.5.0 "," MSXML2. xmlhttp.4.0 "," MSXML2. xmlhttp.3.0 "," MSXML2.
  XMLHTTP "," Microsoft.XMLHTTP "];
      for (var i = 0; i < arrsignatures.length i++) {try {xmlHttp = new ActiveXObject (arrsignatures[i));
    return xmlHttp; ' Catch (oerror) {xmlHttp = false;//ignore}}//throw new Error (' MSXML ' not ' installed on your Syst 
  EM. ");
  if (!xmlhttp && typeof xmlhttprequest!= ' undefined ') {xmlHttp = new XMLHttpRequest ();
return xmlHttp;
var xmlreq = Createxmlhttp (); Send AJAX processing requests (here simply verify the validity of username and password, default correct input: Username and password are test) function Validatepwd (otxt) {var url =/ajaxoperations.aspx?
  Action=xmlop "; VarXmlstr = "<profile>" + "<userName>" + Escape ($ ("txtUserName"). Value) + "</userName>" + "&LT;USERPW
  D> "+ Escape ($ (" txtpwd "). Value) +" </userPwd> "+" </profile> ";
  Xmlreq.open ("Post", url, True); Tell the server you ' re sending it XML xmlreq.setrequestheader ("Content-type", "Text/xml");
  Note here Xmlreq.onreadystatechange = CallBack; Xmlreq.send (XMLSTR); Send XML} function CallBack () {if (xmlreq.readystate = 4) {if (Xmlreq.status =) {alert (xmlreq.respon Setext);
    Receive text} else if (Xmlreq.status = 404) {alert ("requested URL is not found.");
    else if (xmlreq.status = = 403) {alert ("Access denied.");
  else alert ("status is" + Xmlreq.status);

 }
}

jstest.htm file unchanged, ajaxoperations.aspx HTML file content unchanged, server-side. CS processing code is as follows:

AjaxOperations.aspx.cs

Using System;
Using System.Collections.Generic;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Xml;  namespace WebTest2008 {public partial class AjaxOperations:System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {if (!string). IsNullOrEmpty (request["action") && request["action"] = = "Xmlop")//processing XML {XmlDocument doc = new X
        Mldocument (); try {Doc. Load (Request.inputstream);
        Gets the XML data (here you need to pay attention to the method that accepts XML data)} catch (Exception ex) {throw ex;
        } String responsetxt = ""; String tempname = Doc. selectSingleNode ("Profile/username").
        InnerText; String temppwd = Doc. selectSingleNode ("Profile/userpwd").
        InnerText; if (tempname = = "Test" && temppwd = = "Test") {responsetxt = "Verify passed!")
        "; else Responsetxt = "Validation failed!"
        "; Response.Write (Responsetxt);
      Write text}
    }
  }
}

 

Very simple code, run to see it.

2. Receive XML data:

We see that the above two. js files in the processing of returned data are used Xmlreq.responsetext properties, let's try the Xmlreq.responsexml properties:

Testjs.js

This function is equivalent to Document.getelementbyid/document.all function $ (s) {if (document.getElementById) {return eval (' Document.gete Lementbyid ("' + S + '") ');}
else {return eval (' document.all. ' + s);}}
  Creates a XMLHttpRequest object to send an AJAX request function createxmlhttp () {var xmlHttp = false; var arrsignatures = ["MSXML2. xmlhttp.5.0 "," MSXML2. xmlhttp.4.0 "," MSXML2. xmlhttp.3.0 "," MSXML2.
  XMLHTTP "," Microsoft.XMLHTTP "];
      for (var i = 0; i < arrsignatures.length i++) {try {xmlHttp = new ActiveXObject (arrsignatures[i));
      return xmlHttp; ' Catch (oerror) {xmlHttp = false;//ignore}}//throw new Error (' MSXML ' not ' installed on your Syst 
  EM. ");
  if (!xmlhttp && typeof xmlhttprequest!= ' undefined ') {xmlHttp = new XMLHttpRequest ();
return xmlHttp;
var xmlreq = Createxmlhttp (); Send AJAX processing requests (here simply verify the validity of username and password, default correct input: Username and password are test) function Validatepwd (otxt) {var url =/ajaxoperations.aspx?
  Action=xmlop "; VaR xmlstr = "<profile>" + "<userName>" + Escape ($ ("txtUserName"). Value) + "</userName>" + "<user
  Pwd> "+ Escape ($ (" txtpwd "). Value) +" </userPwd> "+" </profile> ";
  Xmlreq.open ("Post", url, True);
  Tell the server you ' re sending it XML xmlreq.setrequestheader ("Content-type", "Text/xml");
  Xmlreq.onreadystatechange = CallBack; Xmlreq.send (XMLSTR); Send XML} function CallBack () {if (xmlreq.readystate = 4) {if (Xmlreq.status =) {var xmldoc = XMLreq . Responsexml;
      Receive XML//var nodes = Xmldoc.childnodes;
      Alert ("Name of the file root tag:" + xmlDoc.documentElement.tagName);
      Alert ("Total number of child nodes in root element: + xmlDoc.documentElement.childNodes.length");
    Alert (xmlDoc.documentElement.childNodes (0). Text);
    else if (xmlreq.status = = 404) {alert ("requested URL is not found.");
    else if (xmlreq.status = = 403) {alert ("Access denied."); else alert (' status is ' + Xmlreq.status);

 }
}

Similarly, the jstest.htm file is unchanged, the contents of the ajaxoperations.aspx HTML file are unchanged, and the server side. CS processing code is modified as follows:

Using System;
Using System.Collections.Generic;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Xml;  namespace WebTest2008 {public partial class AjaxOperations:System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {if (!string). IsNullOrEmpty (request["action") && request["action"] = = "Xmlop")//processing XML {XmlDocument doc = new X
        Mldocument (); try {Doc. Load (Request.inputstream);
        Gets the XML data} catch (Exception ex) {throw ex;
        } String responsexmltxt = ""; String tempname = Doc. selectSingleNode ("Profile/username").
        InnerText; String temppwd = Doc. selectSingleNode ("Profile/userpwd").
        InnerText; if (tempname = = "Test" && temppwd = = "Test") {responsexmltxt = "<?xml version=\" 1.0\ "Encodi" Ng=\ "utf-8\"?> <msg> verify through! </msg> "; Test, simple XML file} ELSE Responsexmltxt = "<?xml version=\ 1.0\" encoding=\ "utf-8\"?><msg> validation failed!
        </msg> "; Response.ContentType = ("Text/xml;charset=utf-8"); This must be set, otherwise the client will not receive the XML file Response.Write (Responsexmltxt) that is written here;
      Write XML Response.End ();

 }
    }
  }
}

Well, the previous two methods are commonly used in the development of the more familiar way, let's look at the third way.

Three, JSON way

JSON's readiness Knowledge:

JSON is a simple data format that is lighter than XML. JSON is the native format of JavaScript, which means that processing JSON-formatted data in JavaScript does not require any special APIs or toolkits. The syntax rule for JSON is simple: an object is an unordered set of ' name/value pairs '. An object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each "name" is followed by a ":" (a colon), and the ' name/value ' pair is separated by a ', ' (comma). Look at an example first:

function Testjson () {
  //define a user (JSON format, which is actually a way to define a JS function (variable))
  var user =
  {
    "username": "Jeff Wong" ,
    "Age": "
    Info": {"tel": "12345678", "cellphone": "13312345678"}, "Address
    "://Array
      [
        {"City" : "Beijing", "postcode": "101110"},
        {"City": "NY City", "postcode": "911119"}
      ]
  }
  alert ( User.username);
  alert (user.age);
  alert (user.info.cellphone);
  alert (user.address[0].city);
  alert (user.address[0].postcode);
  User.username = "Xiao Wang";
  alert (user.username); 
}

The above definition looks very simple, but if there are many fields, the naming method is mixed, the probability of error greatly increased, how to do? This is when you think of generating JSON data in a program way. JSON provides a json.js package that provides several common JSON-processing functions. Download down, (json.js click here to download this site.) ), and then you can simply use Object.tojsonstring () to convert to JSON data. Look at the code:

function car (maker, model, year, color) {
  this.maker = maker;
  This.model = model;
  This.year = year;
  This.color = color;
}
function Testjson () {
  var tempcar = new Car ("VW", "S", 1999, "Yellow");
  Alert (tempcar.tojsonstring ());
}

You can also use the Eval or Parsejson () method to convert JSON data to object:

function Testjson () {
  var str = ' {' name ': ' Jeff Wong ', ' age ': ' A ' address ': ' Beijing '} ';
  var tempobj = eval (' (' + str + ') ');
  Alert (tempobj.tojsonstring ()); Use the Eval method
  var tempObj1 = Str.parsejson ();
  Alert (tempobj1.tojsonstring ()); or use the Parsejson () method
}

About Json.js Learning, please refer to other resources on the Internet, I will not repeat here. Having said so much, the practice link begins:

Ajax sends/receives data using JSON:

This function is equivalent to Document.getelementbyid/document.all function $ (s) {if (document.getElementById) {return eval (' Document.gete Lementbyid ("' + S + '") ');}
else {return eval (' document.all. ' + s);}}
  Creates a XMLHttpRequest object to send an AJAX request function createxmlhttp () {var xmlHttp = false; var arrsignatures = ["MSXML2. xmlhttp.5.0 "," MSXML2. xmlhttp.4.0 "," MSXML2. xmlhttp.3.0 "," MSXML2.
  XMLHTTP "," Microsoft.XMLHTTP "];
      for (var i = 0; i < arrsignatures.length i++) {try {xmlHttp = new ActiveXObject (arrsignatures[i));
    return xmlHttp; ' Catch (oerror) {xmlHttp = false;//ignore}}//throw new Error (' MSXML ' not ' installed on your Syst 
  EM. ");
  if (!xmlhttp && typeof xmlhttprequest!= ' undefined ') {xmlHttp = new XMLHttpRequest ();
return xmlHttp;
var xmlreq = Createxmlhttp (); Send AJAX processing requests (here simply verify the validity of username and password, default correct input: Username and password are test) function Validatepwd (otxt) {var url =/ajaxoperations.aspx?
  Action=jsonop "; //JSON is just text, and because you don't need special coding and each server-side script can handle text data, it's easy to take advantage of JSON and apply it to the server.
  var str = ' {' userName ': ' + $ (' txtUserName '). Value + ' "," userpwd ":" ' + $ ("txtpwd"). Value + ' "};   var jsonstr = Str.parsejson (). toJSONString ();
  You ' re sending it JSON Xmlreq.open ("post", url, True);
  Xmlreq.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
  Xmlreq.onreadystatechange = CallBack; Xmlreq.send ("sendstr=" + jsonstr); Send JSON (interpret JSON on server)} function CallBack () {if (xmlreq.readystate = = 4) {if (Xmlreq.status =) {var J Sonstr = XmlReq.responseText.parseJSON (). toJSONString ();
    Converts to JSON data alert (JSONSTR);
    else if (xmlreq.status = = 404) {alert ("requested URL is not found.");
    else if (xmlreq.status = = 403) {alert ("Access denied.");
  else alert ("status is" + Xmlreq.status);

 }
}

Attach file, ajaxoperations.aspx HTML page does not change, AjaxOperations.aspx.cs code slightly adjusts as follows:

 using System; using System.Collections.Generic; using System.Web; using System.Web.UI
;
Using System.Web.UI.WebControls;  namespace WebTest2008 {public partial class AjaxOperations:System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {if (!string). IsNullOrEmpty (request["action") && request["action"] = = "Jsonop")//Processing JSON {string responsejsontx
        t = ""; String tempstr = request["Sendstr"]. Trim (new char[] {' {', '} '}); Interpreting JSON on the server requires a reference to a component that converts JSON: Json.NET, a simple test here, skipping json.net if (Tempstr.split (new char[] {', '}) [0]. Split (new char[] {': '}) [1] = = "Test\" "&& tempstr.split (new char[] {', '}) [1]. Split (new char[] {': '}) [1] = = "\ test\" ") {responsejsontxt =" {\ "msg\": \ "Verify passed! \"}"; Test with} else Responsejsontxt = "{\" msg\ ": \" validation failed!
        \"}";
        Response.Write (Responsejsontxt);
      Response.End (); }
    }

jstest.html introduce json.js file (must download json.js file, otherwise JS error), as follows:

 
 

I hope this article will help you with Ajax programming.

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.