search
HomeWeb Front-endJS TutorialDetailed 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!


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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

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

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

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

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)