Detailed explanation of ajax data transmission method examples
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
// 此函数等价于document.getElementById /document.all function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } } // 创建 XMLHttpRequest对象,以发送ajax请求 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 is not installed on your system."); if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; } var xmlReq = createXMLHTTP(); // 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是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)); // 发送文本 } 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); } }
Several additional file source codes:
jsTest.htm
<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>
AjaxOperations.aspx
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 = "用户名和密码不匹配!"; string tempStr = Request["userInfos"]; /* 测试用 实际项目中可以对数据库进行检索等等相关操作,这里简化了 */ if (tempStr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)[0] == "test" && tempStr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)[1] == "test") { responseTxt = "验证通过!"; } Response.Write(responseTxt); } } } }
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
// 此函数等价于document.getElementById /document.all function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } } // 创建 XMLHttpRequest对象,以发送ajax请求 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 is not installed on your system."); if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; } var xmlReq = createXMLHTTP(); // 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是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); // 发送XML } 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); } }
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
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") // 处理xml { XmlDocument doc = new XmlDocument(); try { doc.Load(Request.InputStream); //获取xml数据(这里需要注意接受xml数据的方法) } 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); // 写文本 } } } }
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
// 此函数等价于document.getElementById /document.all function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } } // 创建 XMLHttpRequest对象,以发送ajax请求 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 is not installed on your system."); if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; } var xmlReq = createXMLHTTP(); // 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是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); // 发送XML } function callBack() { if (xmlReq.readyState == 4) { if (xmlReq.status == 200) { var xmlDoc = xmlReq.responseXML; // 接收XML // var nodes = xmlDoc.childNodes; // alert("文件根标签的名称: " + xmlDoc.documentElement.tagName); // alert("根元素共有子节点个数: " + 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 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:
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") // 处理xml { XmlDocument doc = new XmlDocument(); try { doc.Load(Request.InputStream); //获取xml数据 } 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>"; // 测试用,简单的xml文件 } else responseXmlTxt = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><msg>验证失败!</msg>"; Response.ContentType = ("text/xml;charset=UTF-8"); // 这里必须要设置,否则客户端接收不到这里写好的xml文件 Response.Write(responseXmlTxt); // 写xml Response.End(); } } } }
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:
function testJson() { //定义一个user(json的格式,其实就是定义一个js函数(变量)的方式而已) 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); }
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:
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": 25,"address":"beijing"}'; var tempObj = eval('(' + str + ')'); alert(tempObj.toJSONString()); //使用eval方法 var tempObj1 = str.parseJSON(); alert(tempObj1.toJSONString()); // 或者使用parseJSON()方法 }
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:
// 此函数等价于document.getElementById /document.all function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } } // 创建 XMLHttpRequest对象,以发送ajax请求 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 is not installed on your system."); if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; } var xmlReq = createXMLHTTP(); // 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test) function validatePwd(oTxt) { var url = "/AjaxOperations.aspx?action=jsonOp"; // JSON就只是文本,由于不需要特殊编码而且每个服务器端脚本都能处理文本数据,所以可以轻松利用JSON并将其应用到服务器。 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); // 发送JSON(在服务器上解释JSON) } function callBack() { if (xmlReq.readyState == 4) { if (xmlReq.status == 200) { var jsonStr = xmlReq.responseText.parseJSON().toJSONString(); //转化为json数据 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); } }
Attached file, the html page of AjaxOperations.aspx has not changed, and the AjaxOperations.aspx.cs code is slightly Make adjustments 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") // 处理JSON { string responseJsonTxt = ""; string tempStr = Request["sendStr"].Trim(new char[] { '{', '}' }); // 在服务器上解释JSON需要引用一个能够转化JSON的组件:Json.Net,这里简单测试,略过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\":\"验证通过!\"}"; // 测试用 } else responseJsonTxt = "{\"msg\":\"验证失败!\"}"; Response.Write(responseJsonTxt); Response.End(); } }
jsTest.html introduces the json.js file (the json.js file must be downloaded, otherwise js will report an error), as follows:
<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>
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!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
