Home  >  Article  >  Web Front-end  >  Detailed explanation of ajax data transmission method examples

Detailed explanation of ajax data transmission method examples

亚连
亚连Original
2018-05-24 14:30:282781browse

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

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

bc0eb9b429be03c09cb1ed32974d3495

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

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

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

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 = &#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()方法
}

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

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

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!

Statement:
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