Table of Contents
1. Ajax receives JSON data" >1. Ajax receives JSON data
1.3.JSON file" >1.3.JSON file
1.4. JSON usage" >1.4. JSON usage
Home Web Front-end JS Tutorial Ajax receives JSON data

Ajax receives JSON data

Jun 24, 2020 am 09:39 AM
ajax json

1. Ajax receives JSON data

JSON: JavaScript Object Notation. JSON is a syntax for storing and exchanging textual information. Because JSON is lighter, more efficient, and easier to parse than XML, the JSON format is generally used to transmit data in front and backends in Ajax.

1.1. Comparison between JSON and XML

JSON

JSON is plain text

JSON has "self-description (human readable)

JSON has a hierarchical structure (values ​​exist within values)

JSON can be parsed through JavaScript eval()

JSON data can be processed using AJAX Transmission

XML

XML is a document structure with complex nodes

XML can be parsed through JavaScript, and it is necessary to loop through the DOM to read node information

XML is thick and Low reading efficiency

1.2.JSON syntax

JSON syntax is a subset of JavaScript syntax.

Rules for JSON syntax:

  • Data in name/value pairs
  • Data separated by commas
  • Curly brackets save the object
  • Square brackets save the array

The writing format of JSON data: name/value pair, that is, the field name (in double quotes), followed by a colon, corresponding to the value. The value of JSON can be: number (integer or floating point number), string (in (in double quotes), logical value (true or false), array (in square brackets), object (in curly brackets), null.

Common JSON syntax writing:

<script type="text/javascript">        var json01 = {}; //json的第一种写法:json对象
        var json02 = []; //json的第二种写法:json数组
        // json对象一般写法
        var json03 = {
            name:"张小三",
            age:45,
            sex:true
        };        
     // json对象标准格式
        var json03_1 = {            
                  "name":"张小三",            
                  "age":45,            
                  "sex":true
        };        
     //json数组
        var json04 = [{
            name:"张小三",
            age:45,
            sex:true
        },{
            name:"李华",
            age:20,
            sex:false
        }
        ];        
      var json05 = [{
            name:"张小三",
            age:45,
            sex:true,
            department:{
                id:1,
                name:"IT部",
                employees:[
                {name:"xxx", age:23},
                {name:"yyy", age:24}
                ]
            }
        },{
            name:"李华",
            age:20,
            sex:false
        }
        ];
</script>
Copy after login

1.3.JSON file

  • The file type of JSON files is ".json"
  • The MIME type of JSON text is "application/json"

1.4. JSON usage

One of the most common uses of JSON is to read JSON-formatted string data from the web server, convert the JSON data into a JavaScript object, and then use the data on the web page.

There are two ways to convert a JSON format string into a JSON object:

①Use JavaScript function eval()

<script type="text/javascript">
        //最标准的json格式:key必须要加双引号
        var formatJson = {
            "name" : "黄小邪",
            "age" : 23,
            "sex" : true
        };
        //①jsonStr转json对象方式一:
        //eval:计算javascript字符串,并把它作为脚本代码来执行
        //前台接收到的是json字符串格式,拿数据需要把字符串转化成json对象
        var jsonStr = '{name : "黄小邪", age : 23, "sex" : true}';
        //注意:使用eval转换jsonStr,必须前后加括号,这里不区分是否标准格式
        var jsonObj = eval("("+ jsonStr +")");
        console.debug(jsonObj);
</script>
Copy after login

②Use JSON parser

## The #eval() function can compile and execute any JavaScript code. Using eval() hides a potential security issue.

It is safer to use a JSON parser to convert a JSON string into a JavaScript object.

The JSON parser can only recognize JSON string text and does not compile scripts. It is relatively faster in parsing and has the convenience of being ready to use.

Use JSON parser:

①You need to import the JSON conversion JSONObj related jar package;

##②The conversion object can be any JSON character Text in string format, but must be in standard JSON format:

//②jsonStr转json对象方式二:
var jsonStr2 = '{"name" : "黄小邪", "age" : 23, "sex" : true}';
//注意:使用JSON.parse转换jsonStr必须保证jsonStr是标准格式的字符串
var jsonObj2 = JSON.parse(jsonStr2);
console.debug(jsonObj2);
Copy after login

1.5. Example of secondary linkage between JSON and Ajax

Here we use JSON string operations and The frontend transmits data in JSON format to demonstrate the operation implementation between JSON and Ajax.

Backstage:

Virtualizes two provinces and cities Domain and provides methods to load and obtain provinces and cities for Servlet to transmit data to the frontend:

City.java:

/**
 * 城市对象
 * 
 */
public class City {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public City() {

    }

    public City(Long id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    /**
     * 根据省份id查询省份中的城市!
     * 
     * @return
     */
    public static List<City> getCityByProvinceId(Long id) {
        
        List<City> citys = new ArrayList<City>();
        
        if (id == 1) {
            citys = Arrays.asList(
                    new City(1L,"成都"),
                    new City(2L,"南充"),
                    new City(3L,"绵阳"),
                    new City(4L,"遂林"),
                    new City(5L,"达州"),
                    new City(6L,"德阳"),
                    new City(7L,"乐山")
            );
        } else if (id == 2) {
            citys = Arrays.asList(
                    new City(11L,"广州"),
                    new City(12L,"佛山"),
                    new City(13L,"东莞")
            );
        } else if (id == 3) {
            citys = Arrays.asList(
                    new City(21L,"昆明"),
                    new City(22L,"玉溪"),
                    new City(23L,"丽江")
            );
        }
        return citys;
    }
}
Copy after login

Province.java:

public class Province {

    private Long id;
    private String name;

    public Province(Long id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Province() {
        super();
    }

    public static List<Province> getAllProvince() {
        List<Province> provinces = new ArrayList<Province>();
        provinces.add(new Province(1L, "四川"));
        provinces.add(new Province(2L, "广东"));
        provinces.add(new Province(3L, "云南"));
        return provinces;
    }
}
Copy after login

Provide a CityProvinceServlet to provide the request address to Ajax:

@WebServlet("/loadData")
public class CityProvinceServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cmd = req.getParameter("cmd");
        String id = req.getParameter("id");
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/json;charset=UTF-8");

        //加载省
        if(cmd.equals("province")){
            List<Province> provinceList = Province.getAllProvince();
            resp.getWriter().print(JSONSerializer.toJSON(provinceList));
            System.out.println("加载省!");
        }
        //加载市
        else {
            if(id != null && id != ""){
                List<City> cityList = City.getCityByProvinceId(Long.parseLong(id));
                resp.getWriter().print(JSONSerializer.toJSON(cityList));
                System.out.println("加载市!");
            }

        }
    }
}
Copy after login

The front desk uses Ajax and JSON to parse the passed JSON format data:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>省市二级联动</title>
    <script type="text/javascript">
        function getAjax(){
            var ajax = null;
            if(XMLHttpRequest){
                ajax = new XMLHttpRequest();
            }else if(ActiveXObject){
                ajax = new ActiveXObject("Microsoft XMLHTTP");
            }
            return ajax;
        }

        function loadProvince() {
            var xhr = getAjax();
            xhr.open("GET", "/loadData?cmd=province");
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4 && xhr.status == 200){
                    //provinces:[{"id":1,"name":"四川"},{"id":2,"name":"广东"},{"id":3,"name":"云南"}]
                    var provinces = xhr.responseText;
                    var jsonObjArr = JSON.parse(provinces);
                    //操作DOM往省级option进行填充数据
                    //首先先创建每个option元素
                    //将jsonObj数据填充进option中
                    jsonObjArr.forEach(
                        function (obj) {
                            var option = document.createElement("option");
                            option.setAttribute("value", obj.id);
                            option.innerHTML = obj.name;
                            document.getElementById("province").appendChild(option);
                        }
                    );
                }
            };
            xhr.send();
        }
        loadProvince();

        function loadCity() {
            //得到id
            var id = document.getElementById("province").value;
            //如果是请选择,对应就不加载
            if(id == -1){
                document.getElementById("city").innerHTML = "<option>----请选择----</option>";
                return;
            }
            //每次加载都初始化一次
            document.getElementById("city").innerHTML = "";
            var xhr = getAjax();
            xhr.open("GET", "/loadData?cmd=city&id=" + id);
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4 && xhr.status == 200){
                    //[{"id":1,"name":"成都"},{"id":2,"name":"南充"},{"id":3,"name":"绵阳"},{"id":4,"name":"遂林"},{"id":5,"name":"达州"},
                    // {"id":6,"name":"德阳"},{"id":7,"name":"乐山"}]
                    var cityes = xhr.responseText;
                    var jsonObjArr = JSON.parse(cityes);
                    jsonObjArr.forEach(
                        function (obj) {
                            var option = document.createElement("option");
                            option.setAttribute("value", obj.id);
                            option.innerHTML = obj.name;
                            document.getElementById("city").appendChild(option);
                        }
                    );
                    //去除掉----请选择------
                    document.getElementById("city").options.remove(0);
                }
            };
            xhr.send();
        }
    </script>
</head>
<body>
    省级:<select id="province" onchange="loadCity()">
        <option value="-1">----请选择----</option>
    </select>
    市级:<select id="city">
        <option>----请选择----</option>
    </select>
</body>
</html>
Copy after login

The effect is as follows:

Recommended tutorial: "

JS Tutorial

"

The above is the detailed content of Ajax receives JSON data. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

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)

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.

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

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

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

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

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

See all articles