Examples of ajax data transmission methods,
This document describes the ajax data transmission method. We will share this with you for your reference. The details are as follows:
When sending and receiving information in an asynchronous application, you can use plain text and XML as the data format (For details, refer to the Ajax usage example of jQuery learning notes). another popular method is JSON (JavaScript Object Notation ). Well, the following example shows how these three data formats are used in ajax asynchronous applications.
I. plain text
1. Send/receive data:
Code is cheap. Check the Code:
TestJs. js
// This function is equivalent to document. getElementById/document. allfunction $ (s) {if (document. getElementById) {return eval ('document. getElementById ("'+ s +'") ');} else {return eval ('document. all. '+ s) ;}// create the XMLHttpRequest object to send the 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 "]; f Or (var I = 0; I <arrSignatures. length; I ++) {try {xmlHttp = new ActiveXObject (arrSignatures [I]); return xmlHttp;} catch (oError) {xmlHttp = false; // ignore }}// throw new Error ("MSXML is not installed on your system. "); if (! XmlHttp & typeof XMLHttpRequest! = 'Undefined') {xmlHttp = new XMLHttpRequest ();} return xmlHttp;} var xmlReq = createXMLHTTP (); // send an ajax request (here, the user name and password are verified to be valid. By default, the correct user name and password are all 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 = 200) {alert (xmlReq. responseText); // receives the 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 );}}
Source code of several additional files:
JsTest.htm
<Html>
AjaxOperations. aspx
Copy codeThe Code is 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 = "the user name and password do not match! "; String tempStr = Request [" userInfos "];/* You can search the database and perform other operations in the actual project. The */if (tempStr. split (new char [] {'/'}, StringSplitOptions. removeEmptyEntries) [0] = "test" & tempStr. split (new char [] {'/'}, StringSplitOptions. removeEmptyEntries) [1] = "test") {responseTxt = "verified! ";}Response. Write (responseTxt );}}}}
Save the files one by one, ctrl + F5, and run it.
The above method is the simplest, most direct, and most effective method. Skillful Use of the best.
Ii. XML Method
1. Send XML data
TestJs. js
// This function is equivalent to document. getElementById/document. allfunction $ (s) {if (document. getElementById) {return eval ('document. getElementById ("'+ s +'") ');} else {return eval ('document. all. '+ s) ;}// create the XMLHttpRequest object to send the 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 "]; f Or (var I = 0; I <arrSignatures. length; I ++) {try {xmlHttp = new ActiveXObject (arrSignatures [I]); return xmlHttp;} catch (oError) {xmlHttp = false; // ignore }}// throw new Error ("MSXML is not installed on your system. "); if (! XmlHttp & typeof XMLHttpRequest! = 'Undefined') {xmlHttp = new XMLHttpRequest ();} return xmlHttp;} var xmlReq = createXMLHTTP (); // send an ajax request (here, the user name and password are verified to be valid. By default, the correct user name and password are all test) function validatePwd (oTxt) {var url = "/AjaxOperations. aspx? Action = xmlOp "; var xmlStr =" <profile> "+" <userName> "+ escape ($ (" txtUserName "). value) + "</userName>" + "<userPwd>" + escape ($ ("txtPwd "). value) + "</userPwd>" + "</profile>"; xmlReq. open ("post", url, true); // Tell the server you're sending it XML xmlReq. setRequestHeader ("Content-Type", "text/xml"); // pay attention to xmlReq. onreadystatechange = callBack; xmlReq. send (xmlStr); // send XML} function callBack () {if (xmlReq. readyState = 4) {if (xmlReq. status = 200) {alert (xmlReq. responseText); // receives the 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 );}}
The jsTest.htm file remains unchanged, and the HTML file content of AjaxOperations. aspx remains unchanged. The 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") // process xml {XmlDocument doc = new XmlDocument (); try {doc. load (Request. inputStream); // get xml data (here you need to pay attention to the method of accepting 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 = "verified! ";} Else responseTxt =" Verification Failed! "; Response. Write (responseTxt); // Write text }}}}
Simple code. Run it.
2. Receive XML data:
We can see that the xmlReq. responseText attribute is used for processing returned data in the above two. js files. Let's try the xmlReq. responseXML attribute:
TestJs. js
// This function is equivalent to document. getElementById/document. allfunction $ (s) {if (document. getElementById) {return eval ('document. getElementById ("'+ s +'") ');} else {return eval ('document. all. '+ s) ;}// create the XMLHttpRequest object to send the 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 "]; f Or (var I = 0; I <arrSignatures. length; I ++) {try {xmlHttp = new ActiveXObject (arrSignatures [I]); return xmlHttp;} catch (oError) {xmlHttp = false; // ignore }}// throw new Error ("MSXML is not installed on your system. "); if (! XmlHttp & typeof XMLHttpRequest! = 'Undefined') {xmlHttp = new XMLHttpRequest ();} return xmlHttp;} var xmlReq = createXMLHTTP (); // send an ajax request (here, the user name and password are verified to be valid. By default, the correct user name and password are all test) function validatePwd (oTxt) {var url = "/AjaxOperations. aspx? Action = xmlOp "; var xmlStr =" <profile> "+" <userName> "+ escape ($ (" txtUserName "). value) + "</userName>" + "<userPwd>" + 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 = 200) {var xmlDoc = xmlReq. responseXML; // receive XML // var nodes = xmlDoc. childNodes; // alert ("name of the file root tag:" + xmlDoc.doc umentElement. tagName); // alert ("Total number of subnodes in the root element:" + xmlDoc.doc umentElement. childNodes. length); alert(xmlDoc.doc umentElement. 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 );}}
In the same example, the jstest.htm file remains unchanged, the HTML file content of AjaxOperations. aspx remains unchanged, and the server-side. CS processing code is slightly 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") // process xml {XmlDocument doc = new XmlDocument (); try {doc. load (Request. inputStream); // get 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" & temp Pwd = "test") {responseXmlTxt = "<? Xml version = \ "1.0 \" encoding = \ "UTF-8 \"?> <Msg> Verification passed! </Msg> "; // for testing, simple xml file} else responseXmlTxt =" <? Xml version = \ "1.0 \" encoding = \ "UTF-8 \"?> <Msg> Verification Failed! </Msg> "; Response. contentType = ("text/xml; charset = UTF-8"); // you must set it here, otherwise the client will not receive the xml file Response written here. write (responseXmlTxt); // Write xml Response. end ();}}}}
Well, the first two methods are familiar to developers at ordinary times. Let's take a look at the third method.
Iii. JSON Mode
Json preparation knowledge:
Json is a simple data format, which is lighter than xml. Json is the native format of JavaScript, which means that no special API or toolkit is required to process json data in JavaScript. Json syntax rules are actually very simple: the object is an unordered set of 'name/value' pairs. An object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon); "," (comma) is used to separate the "name/value" pairs. Let's take a look at the example first:
Function testJson () {// defines a user (json format, which is actually a js function (variable) method) var user = {"username ": "jeff wong", "age": 25, "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 method looks simple, but if there are many fields and the naming method is mixed, the error probability is greatly increased. What should I do? At this time, you will think of using a program to generate json data. Json provides the json. js package and provides several common json processing functions. Download it. (Click here to download json. js .) , And then you can simply use object. toJSONString () to convert it into json data. Check 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 an object:
Function testJson () {var str = '{"name": "jeff wong", "age": 25, "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}
For details about how to learn json. js, refer to other online resources. I will not go into details here. After talking about this, the practical process begins:
Ajax uses json to send/receive data:
// This function is equivalent to document. getElementById/document. allfunction $ (s) {if (document. getElementById) {return eval ('document. getElementById ("'+ s +'") ');} else {return eval ('document. all. '+ s) ;}// create the XMLHttpRequest object to send the 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 "]; f Or (var I = 0; I <arrSignatures. length; I ++) {try {xmlHttp = new ActiveXObject (arrSignatures [I]); return xmlHttp;} catch (oError) {xmlHttp = false; // ignore }}// throw new Error ("MSXML is not installed on your system. "); if (! XmlHttp & typeof XMLHttpRequest! = 'Undefined') {xmlHttp = new XMLHttpRequest ();} return xmlHttp;} var xmlReq = createXMLHTTP (); // send an ajax request (here, the user name and password are verified to be valid. By default, the correct user name and password are all test) function validatePwd (oTxt) {var url = "/AjaxOperations. aspx? Action = jsonOp "; // JSON is just text. Because no special encoding is required and every server script can process text data, JSON can be easily used and applied 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 (JSON interpreted on the server)} function callBack () {if (xmlReq. readyState = 4) {if (xmlReq. status = 200) {var jsonStr = xmlReq. responseText. parseJSON (). toJSONString (); // convert 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 );}}
The html page of AjaxOperations. aspx is not changed. The AjaxOperations. aspx. cs code is slightly adjusted 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") // process JSON {string responseJsonTxt = ""; string tempStr = Request ["sendStr"]. trim (new char [] {','}); // parse JSON on the server and reference a component that can convert JSON: Json. net, simple test here, skipped Json. net if (tempStr. split (new char [] {','}) [0]. split (new char [] {':'}) [1] = "\" test \ "" & tempStr. split (new char [] {','}) [1]. split (new char [] {':'}) [1] = "\" t Est \ "") {responseJsonTxt = "{\" msg \ ": \" verified! \ "}"; // Test with} else responseJsonTxt = "{\" msg \ ": \" Verification Failed! \ "}"; Response. Write (responseJsonTxt); Response. End ();}}
JsTest.html introduces the json. js file (the json. js file must be downloaded; otherwise, js reports an error) as follows:
<Html>
I hope this article will help you with ajax programming.
Articles you may be interested in:
- How to transmit large data using ajax in JQuery
- AJAX Asynchronous Data Transmission
- Sample Code for asynchronous transmission and verification implemented by Ajax
- Example of interaction between Ajax asynchronous transmission and PHP
- Sample Code for Ajax synchronization and asynchronous transmission
- Implementation of asynchronous transmission technology using ThinkPHP's built-in ThinkAjax
- How to Use AJAX to encode special AJAX characters in GB2312
- Ajax objects include post and get asynchronous transmission methods.