Home>Article>Web Front-end> Ajax receives JSON data

Ajax receives JSON data

hzc
hzc forward
2020-06-24 09:39:17 3167browse

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:

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

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

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 getCityByProvinceId(Long id) { List citys = new ArrayList(); 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; } }

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 getAllProvince() { List provinces = new ArrayList(); provinces.add(new Province(1L, "四川")); provinces.add(new Province(2L, "广东")); provinces.add(new Province(3L, "云南")); return provinces; } }

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

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

    省市二级联动  
省级: 市级:

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:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete