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> 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>
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> //最标准的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>
②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<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; } }</city></city></city>
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; } }</province></province></province>
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("加载市!"); } } } }</city></province>
The front desk uses Ajax and JSON to parse the passed JSON format data:
nbsp;html> <meta> <title>省市二级联动</title> <script> 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>----请选择----"; 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> 省级:<select> <option>----请选择----</option> </select> 市级:<select> <option>----请选择----</option> </select>
The effect is as follows:
Recommended 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!

404页面基础配置404错误是www网站访问容易出现的错误。最常见的出错提示:404notfound。404错误页的设置对网站seo有很大的影响,而设置不当,比如直接转跳主页等,会被搜索引擎降权拔毛。404页面的目的应该是告诉用户:你所请求的页面是不存在的,同时引导用户浏览网站其他页面而不是关掉窗口离去。搜索引擎通过http状态码来识别网页的状态。当搜索引擎获得了一个错误链接时,网站应该返回404状态码,告诉搜索引擎放弃对该链接的索引。而如果返回200或302状态码,搜索引擎就会为该链接建立索引

Scrapy是一个开源的Python爬虫框架,它可以快速高效地从网站上获取数据。然而,很多网站采用了Ajax异步加载技术,使得Scrapy无法直接获取数据。本文将介绍基于Ajax异步加载的Scrapy实现方法。一、Ajax异步加载原理Ajax异步加载:在传统的页面加载方式中,浏览器发送请求到服务器后,必须等待服务器返回响应并将页面全部加载完毕才能进行下一步操

作为一种基于MVC模式的PHP框架,CakePHP已成为许多Web开发人员的首选。它的结构简单,易于扩展,而其中的AJAX技术更是让开发变得更加高效。在本文中,将介绍如何使用CakePHP中的AJAX。什么是AJAX?在介绍如何在CakePHP中使用AJAX之前,我们先来了解一下什么是AJAX。AJAX是“异步JavaScript和XML”的缩写,是指一种在

ajax传递中文乱码的解决办法:1、设置统一的编码方式;2、服务器端编码;3、客户端解码;4、设置HTTP响应头;5、使用JSON格式。详细介绍:1、设置统一的编码方式,确保服务器端和客户端使用相同的编码方式,通常情况下,UTF-8是一种常用的编码方式,因为它可以支持多种语言和字符集;2、服务器端编码,在服务器端,确保将中文数据以正确的编码方式进行编码,再传递给客户端等等。

ajax重构指的是在不改变软件现有功能的基础上,通过调整程序代码改善软件的质量、性能,使其程序的设计模式和架构更合理,提高软件的扩展性和维护性;Ajax的实现主要依赖于XMLHttpRequest对象,由于该对象的实例在处理事件完成后就会被销毁,所以在需要调用它的时候就要重新构建。

jquery ajax报错403是因为前端和服务器的域名不同而触发了防盗链机制,其解决办法:1、打开相应的代码文件;2、通过“public CorsFilter corsFilter() {...}”方法设置允许的域即可。

当提交表单时,捕获提交过程并尝试运行以下代码片段来上传文件-//File1varmyFile=document.getElementById('fileBox').files[0];varreader=newFileReader();reader.readAsText(file,'UTF-8');reader.onload=myFunc;functionmyFunc(event){ varres

CSRF代表跨站请求伪造。CSRF是未经授权的用户冒充授权执行的恶意活动。Laravel通过为每个活动用户会话生成csrf令牌来保护此类恶意活动。令牌存储在用户的会话中。如果会话发生变化,它总是会重新生成,因此每个会话都会验证令牌,以确保授权用户正在执行任何任务。以下是访问csrf_token的示例。生成csrf令牌您可以通过两种方式获取令牌。通过使用$request→session()→token()直接使用csrf_token()方法示例<?phpnamespaceApp\Http\C


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

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.