This article mainly introduces the ajax data transmission method. It summarizes the principles of ajax data transmission and the specific implementation techniques for transmitting text, xml and json format data with a more detailed analysis in the form of examples. It has certain reference value and is needed. Friends can refer to
This article describes the ajax data transmission method with examples. Share it with everyone for your reference, the details are as follows:
When sending and receiving information in asynchronous applications, you can usually choose plain text and XML as the data format (please refer to "JQuery Study Notes: Ajax Usage Example Detailed Explanation" 》), there is another popular method now: JSON (JavaScript Object Notation). Okay, here are examples of the asynchronous application of these three data formats in ajax.
1. Plain text mode
1. Send/receive data:
Code is cheap. Look at the code:
testJs.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | function $(s) { if (document.getElementById) { return eval(& #39;document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
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 ;
}
}
if (!xmlHttp && typeof XMLHttpRequest != & #39;undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlReq = createXMLHTTP();
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));
}
function callBack() {
if (xmlReq.readyState == 4) {
if (xmlReq.status == 200) {
alert(xmlReq.responseText);
}
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);
}
}
|
Copy after login
Several additional file source codes:
jsTest.htm
1 2 3 4 5 6 7 8 9 10 11 12 | <html>
<head>
<title>js test</title>
<script src= "js/testJs.js" type= "text/javascript" ></script>
</head>
<body>
<form id= "form1" >
<p>
用户名:<input id= "txtUserName" name= "txtUserName" type= "text" /> 密码:<input id= "txtPwd" name= "txtPwd" type= "password" onblur= "validatePwd(this)" /></p>
</form>
</body>
</html>
|
Copy after login
AjaxOperations.aspx
<%@ Page Language="C#" AutoEventWireup=" true" CodeBehind="AjaxOperations.aspx.cs" Inherits="WebTest2008.AjaxOperations" %>
AjaxOperations.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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 = "用户名和密码不匹配!" ;
string tempStr = Request[ "userInfos" ];
if (tempStr.Split( new char[] { & #39;/' }, StringSplitOptions.RemoveEmptyEntries)[0] == "test" && tempStr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)[1] == "test")
{
responseTxt = "验证通过!" ;
}
Response.Write(responseTxt);
}
}
}
}
|
Copy after login
Save the files one by one, ctrl F5, and try running Bar.
The above method is the simplest, most direct and most effective method. Best used skillfully.
2. XML method
1. Send XML data
testJs.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | function $(s) { if (document.getElementById) { return eval(& #39;document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
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 ;
}
}
if (!xmlHttp && typeof XMLHttpRequest != & #39;undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlReq = createXMLHTTP();
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 );
xmlReq.setRequestHeader( "Content-Type" , "text/xml" );
xmlReq.onreadystatechange = callBack;
xmlReq.send(xmlStr);
}
function callBack() {
if (xmlReq.readyState == 4) {
if (xmlReq.status == 200) {
alert(xmlReq.responseText);
}
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);
}
}
|
Copy after login
jsTest.htm file remains unchanged. The content of the HTML file of AjaxOperations.aspx remains unchanged, and the server-side .CS processing code is as follows:
AjaxOperations.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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" )
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Request.InputStream);
}
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 = "验证通过!" ;
}
else responseTxt = "验证失败!" ;
Response.Write(responseTxt);
}
}
}
}
|
Copy after login
It’s a very simple code, let’s run it and see.
2. Receive XML data:
We see that the xmlReq.responseText attribute is used in the above two .js files when processing return data. Let’s try the xmlReq.responseXML attribute. :
testJs.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | function $(s) { if (document.getElementById) { return eval(& #39;document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
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 ;
}
}
if (!xmlHttp && typeof XMLHttpRequest != & #39;undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlReq = createXMLHTTP();
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 );
xmlReq.setRequestHeader( "Content-Type" , "text/xml" );
xmlReq.onreadystatechange = callBack;
xmlReq.send(xmlStr);
}
function callBack() {
if (xmlReq.readyState == 4) {
if (xmlReq.status == 200) {
var xmlDoc = xmlReq.responseXML;
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);
}
}
|
Copy after login
Similarly, the jsTest.htm file remains unchanged, the content of the HTML file of AjaxOperations.aspx remains unchanged, and the server-side .CS processing code is slightly modified as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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" )
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Request.InputStream);
}
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\" encoding=\"utf-8\" ?> <msg>验证通过!</msg>" ;
}
else responseXmlTxt = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><msg>验证失败!</msg>" ;
Response.ContentType = ( "text/xml;charset=UTF-8" );
Response.Write(responseXmlTxt);
Response.End();
}
}
}
}
|
Copy after login
Okay, the first two methods are familiar to everyone in daily development. Let’s take a look at the third method.
3. JSON method
Preparatory knowledge of json:
json is a simple data format that is more lightweight than xml. json is the native format of JavaScript, which means that processing json-formatted data in JavaScript does not require any special API or toolkit. The syntax rules of json are actually very simple: an object is an unordered collection of "name/value pairs". An object starts with "{" (left bracket) and ends with "}" (right bracket). Each "name" is followed by a ":" (colon); "name/value" pairs are separated by a "," (comma). Let’s look at an example first:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function testJson() {
var user =
{
"username" : "jeff wong" ,
"age" : 25,
"info" : { "tel" : "12345678" , "cellphone" : "13312345678" },
"address" :
[
{ "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);
}
|
Copy after login
The above definition method seems very simple, but what should we do if there are many fields and mixed naming methods, and the probability of errors is greatly increased? At this time you will think of using a program to generate json data. json provides the json.js package, which specifically provides several commonly used json processing functions. Download it (json.js click here to download from this site.), import it and then simply use object.toJSONString() to convert it into json data. Look at the code:
1 2 3 4 5 6 7 8 9 10 | 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());
}
|
Copy after login
You can also use the eval or parseJSON() method to convert json data to object:
1 2 3 4 5 6 7 | function testJson() {
var str = & #39;{ "name": "jeff wong", "age": 25,"address":"beijing"}';
var tempObj = eval(& #39;(' + str + ')');
alert(tempObj.toJSONString());
var tempObj1 = str.parseJSON();
alert(tempObj1.toJSONString());
}
|
Copy after login
For learning about json.js, please refer to other resources on the Internet, I will not cover it here. No more details. Having said so much, the practical part begins:
ajax uses json to send/receive data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | function $(s) { if (document.getElementById) { return eval(& #39;document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
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 ;
}
}
if (!xmlHttp && typeof XMLHttpRequest != & #39;undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlReq = createXMLHTTP();
function validatePwd(oTxt) {
var url = "/AjaxOperations.aspx?action=jsonOp" ;
var str = & #39;{ "userName":"' + $("txtUserName").value + '", "userPwd": "' + $("txtPwd").value + '"}';
var jsonStr = str.parseJSON().toJSONString();
xmlReq.open( "post" , url, true );
xmlReq.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded" );
xmlReq.onreadystatechange = callBack;
xmlReq.send( "sendStr=" + jsonStr);
}
function callBack() {
if (xmlReq.readyState == 4) {
if (xmlReq.status == 200) {
var jsonStr = xmlReq.responseText.parseJSON().toJSONString();
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);
}
}
|
Copy after login
Attached file, the html page of AjaxOperations.aspx has not changed, and the AjaxOperations.aspx.cs code is slightly Make adjustments as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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" )
{
string responseJsonTxt = "" ;
string tempStr = Request[ "sendStr" ].Trim( new char[] { & #39;{', '}' }); // 在服务器上解释JSON需要引用一个能够转化JSON的组件:Json.Net,这里简单测试,略过Json.Net
if (tempStr.Split( new char[] { & #39;,' })[0].Split(new char[] { ':' })[1] == "\"test\"" && tempStr.Split(new char[] { ',' })[1].Split(new char[] { ':' })[1] == "\"test\"")
{
responseJsonTxt = "{\"msg\":\"验证通过!\"}" ;
}
else responseJsonTxt = "{\"msg\":\"验证失败!\"}" ;
Response.Write(responseJsonTxt);
Response.End();
}
}
|
Copy after login
jsTest.html introduces the json.js file (the json.js file must be downloaded, otherwise js will report an error), as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <html>
<head>
<title>js test</title>
<script src= "js/json.js" type= "text/javascript" ></script>
<script src= "js/testJs.js" type= "text/javascript" ></script>
</head>
<body>
<form id= "form1" >
<p>
用户名:<input id= "txtUserName" name= "txtUserName" type= "text" />
密码:<input id= "txtPwd" name= "txtPwd" type= "password" onblur= "validatePwd(this)" /></p>
</form>
</body>
</html>
|
Copy after login
The above is what I compiled for everyone, I hope It will be helpful to everyone in the future.
Related articles:
Simple search implementation method based on ajax
JS and jQuery method to terminate the ajax request being sent
Solution to IE caching problem during ajax call
The above is the detailed content of Detailed explanation of ajax data transmission method examples. For more information, please follow other related articles on the PHP Chinese website!