


Detailed explanation of jQuery Ajax asynchronous processing of Json data
Let’s look at an official example first
Use AJAX request to obtain JSON data and output the result:
$("button").click(function(){ $.getJSON("demo_ajax_json.js",function(result){ $.each(result, function(i, field){ $("div").append(field + " "); }); }); });
This function is the abbreviation of Ajax function, which is equivalent to:
$.ajax({ url: url, data: data, success: callback, dataType: json });
Data sent to the server can be appended to the URL as a query string. If the value of the data parameter is an object (map), it is converted to a string and URL-encoded before being appended to the URL.
The return data passed to callback can be a JavaScript object or an array defined in a JSON structure, and is parsed using the $.parseJSON() method.
Load JSON data from test.js and display a name field data in the JSON data:
$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });
An asp.net instance
First give the json data to be transferred: [{"demoData ":"This Is The JSON Data"}]
1, use an ordinary aspx page to process it
I think this method is the easiest to process, look at the code below
$.ajax({ type: "post", url: "Default.aspx", dataType: "json", success: function (data) { $("input#showTime").val(data[0].demoData); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); } });
Here is the code for passing data in the background
Response.Clear(); Response.Write("[{"demoData":"This Is The JSON Data"}]"); Response.Flush(); Response.End();
This processing method directly parses the passed data into json data, which means that the front-end js code here may directly parse these data into json object data. Instead of string data, such as data[0].demoData, this json object data is used directly here
2, use webservice (asmx) to process
This processing method will not transfer the passed data Treated as json object data, but processed as a string, the following code
$.ajax({ type: "post", url: "JqueryCSMethodForm.asmx/GetDemoData", dataType: "json",/*这句可用可不用,没有影响*/ contentType: "application/json; charset=utf-8", success: function (data) { $("input#showTime").val(eval('(' + data.d + ')')[0].demoData); //这里有两种对数据的转换方式,两处理方式的效果一样//$("input#showTime").val(eval(data.d)[0].demoData); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); } });
The following is the asmx method code
[WebMethod] public static string GetDemoData() { return "[{"demoData":"This Is The JSON Data"}]"; }
This processing method here will pass back the json The data is processed as a string, so the data must be eval processed so that it can become a real json object data.
Let's take a look at the html template first:
<table id="datas" border="1" cellspacing="0" style="border-collapse: collapse"> <tr> <th> 订单ID</th> <th> 客户ID</th> <th> 雇员ID</th> <th> 订购日期</th> <th> 发货日期</th> <th> 货主名称</th> <th> 货主地址</th> <th> 货主城市</th> <th> 更多信息</th> </tr> <tr id="template"> <td id="OrderID"> </td> <td id="CustomerID"> </td> <td id="EmployeeID"> </td> <td id="OrderDate"> </td> <td id="ShippedDate"> </td> <td id="ShippedName"> </td> <td id="ShippedAddress"> </td> <td id="ShippedCity"> </td> <td id="more"> </td> </tr> </table>
Be sure to pay attention are all the id attributes inside, this is a key. Let's take a look at the code for AJAX request and data binding
$.ajax({ type: "get",//使用get方法访问后台 dataType: "json",//返回json格式的数据 url: "BackHandler.ashx",//要访问的后台地址 data: "pageIndex=" + pageIndex,//要发送的数据 complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示 success: function(msg){//msg为返回的数据,在这里做数据绑定 var data = msg.table; $.each(data, function(i, n){ var row = $("#template").clone(); row.find("#OrderID").text(n.订单ID); row.find("#CustomerID").text(n.客户ID); row.find("#EmployeeID").text(n.雇员ID); row.find("#OrderDate").text(ChangeDate(n.订购日期)); if(n.发货日期!== undefined) row.find("#ShippedDate").text(ChangeDate(n.发货日期)); row.find("#ShippedName").text(n.货主名称); row.find("#ShippedAddress").text(n.货主地址); row.find("#ShippedCity").text(n.货主城市); row.find("#more").html("<a href=OrderInfo.aspx?id=" + n.订单ID + "&pageindex="+pageIndex+"> More</a>"); row.attr("id","ready");//改变绑定好数据的行的id row.appendTo("#datas");//添加到模板的容器中 });
This is jQuery's AJAX method. The returned data is not complicated. It mainly explains how to display the data on the page according to the definition of the template. The first is this "var row = $("#template").clone();" first copy the template, and then row.find("#OrderID").text(n. order ID);, indicating that it is found For the tag with id=OrderID, set its innerText to the corresponding data. Of course, it can also be set to data in html format. Or convert the data into the required format through external functions, such as here row.find("#OrderDate").text(ChangeDate(n. order date)); It feels a bit like a server control doing template binding data.
All of these are placed in a static page, and data is only obtained from the background through the AJAX method. All html codes are as follows:
test1
<table id="datas" border="1" cellspacing="0" style="border-collapse: collapse"> <tr> <th> 订单ID</th> <th> 客户ID</th> <th> 雇员ID</th> <th> 订购日期</th> <th> 发货日期</th> <th> 货主名称</th> <th> 货主地址</th> <th> 货主城市</th> <th> 更多信息</th> </tr> <tr id="template"> <td id="OrderID"> </td> <td id="CustomerID"> </td> <td id="EmployeeID"> </td> <td id="OrderDate"> </td> <td id="ShippedDate"> </td> <td id="ShippedName"> </td> <td id="ShippedAddress"> </td> <td id="ShippedCity"> </td> <td id="more"> </td> </tr> </table>LOADING....
PageData.js includes the above AJAX request and binding data The js of the code does not even use the form on the entire page. What are the benefits of doing so. Look at the following template
<ul id="datas"> <li id="template"> <span id="OrderID"> fsdfasdf </span> <span id="CustomerID"> </span> <span id="EmployeeID"> </span> <span id="OrderDate"> </span> <span id="ShippedDate"> </span> <span id="ShippedName"> </span> <span id="ShippedAddress"> </span> <span id="ShippedCity"> </span> <span id="more"> </span> </li> </ul>
and still pay attention to the id attribute. Everyone should understand after seeing this that no matter what form of expression is used, as long as the id attribute is the same, the data can be bound to the corresponding location. In this case, those of us who are programmers will not modify the code due to the modification of the artist, and the artist only needs to make HTML, and there is no need to make templates for the server controls (but I have not encountered such an artist, They are all designed by the artist and I will change them into server control templates).
For more detailed explanations of jQuery Ajax asynchronous processing of Json data, please pay attention to the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

This article discusses how to use jQuery to obtain and set the inner margin and margin values of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c
