Home Web Front-end JS Tutorial Detailed explanation of ajax data transmission method examples

Detailed explanation of ajax data transmission method examples

May 24, 2018 pm 02:30 PM
ajax data transmission Detailed explanation

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 != &#39;undefined&#39;) {
    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);
  }
}
Copy after login

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>
Copy after login

AjaxOperations.aspx

<%@ 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 = "用户名和密码不匹配!";
        string tempStr = Request["userInfos"];
        /* 测试用 实际项目中可以对数据库进行检索等等相关操作,这里简化了 */
        if (tempStr.Split(new char[] { &#39;/&#39; }, StringSplitOptions.RemoveEmptyEntries)[0] == "test" && tempStr.Split(new char[] { &#39;/&#39; }, 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

// 此函数等价于document.getElementById /document.all
function $(s) { if (document.getElementById) { return eval(&#39;document.getElementById("&#39; + s + &#39;")&#39;); } else { return eval(&#39;document.all.&#39; + 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 != &#39;undefined&#39;) {
    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&#39;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);
  }
}
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

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); // 写文本
      }
    }
  }
}
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

// 此函数等价于document.getElementById /document.all
function $(s) { if (document.getElementById) { return eval(&#39;document.getElementById("&#39; + s + &#39;")&#39;); } else { return eval(&#39;document.all.&#39; + 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 != &#39;undefined&#39;) {
    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&#39;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);
  }
}
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:

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

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

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:

function testJson() {
  var str = &#39;{ "name": "jeff wong", "age": 25,"address":"beijing"}&#39;;
  var tempObj = eval(&#39;(&#39; + str + &#39;)&#39;);
  alert(tempObj.toJSONString()); //使用eval方法
  var tempObj1 = str.parseJSON();
  alert(tempObj1.toJSONString()); // 或者使用parseJSON()方法
}
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:

// 此函数等价于document.getElementById /document.all
function $(s) { if (document.getElementById) { return eval(&#39;document.getElementById("&#39; + s + &#39;")&#39;); } else { return eval(&#39;document.all.&#39; + 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 != &#39;undefined&#39;) {
    xmlHttp = new XMLHttpRequest();
  }
  return xmlHttp;
}
var xmlReq = createXMLHTTP();
// 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test)
function validatePwd(oTxt) {
  var url = "/AjaxOperations.aspx?action=jsonOp";
  // JSON就只是文本,由于不需要特殊编码而且每个服务器端脚本都能处理文本数据,所以可以轻松利用JSON并将其应用到服务器。
  var str = &#39;{ "userName":"&#39; + $("txtUserName").value + &#39;", "userPwd": "&#39; + $("txtPwd").value + &#39;"}&#39;;
  var jsonStr = str.parseJSON().toJSONString();   // you&#39;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);
  }
}
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:

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[] { &#39;{&#39;, &#39;}&#39; }); // 在服务器上解释JSON需要引用一个能够转化JSON的组件:Json.Net,这里简单测试,略过Json.Net
        if (tempStr.Split(new char[] { &#39;,&#39; })[0].Split(new char[] { &#39;:&#39; })[1] == "\"test\"" && tempStr.Split(new char[] { &#39;,&#39; })[1].Split(new char[] { &#39;:&#39; })[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:

<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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

See all articles