search
HomeWeb Front-endJS TutorialHow $.ajax() gets json data from the server

This time I will bring you how $.ajax() obtains json data from the server, and how $.ajax() obtains json data from the server. What are the precautions?The following is a practical case, one Get up and take a look.

The editor below will share with you a summary of several ways to obtain json data from the server based on the $.ajax() method. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor and take a look

1. What is json

json is a data structure that replaces xml. Compared with xml, it is smaller but has strong descriptive capabilities. The network transmission data uses less traffic and is faster. quick.

json is a string of characters, marked with the following symbols.

{Key-value pair}: json object

[{},{},{}]: json array

"": Double quotes are attributes or values

: : The colon is preceded by the key and followed by the value (this value can be a value of the basic data type, or an array or object), so {"age": 18} is understandable is a json object containing age 18, and [{"age": 18},{"age": 20}] represents a json array containing two objects. You can also use {"age":[18,20]} to simplify the above json array, which is an object with an age array.

two. The value of the dataType attribute in the $.ajax() method

The dataType attribute in the $.ajax() method is required to be a String type parameter, and the data type expected to be returned by the server. If not specified, JQuery will automatically return responseXML or responseText [explained in Part 3] based on the http package mime information, and pass it as the callback function parameter. The available types are as follows:

xml: Returns an XML document that can be processed with JQuery.

html: Returns plain text HTML information; the included script tag will be executed when inserted into the DOM.

script: Returns plain text JavaScript code. Results are not cached automatically. Unless cache parameters are set. Note that when making remote requests (not under the same domain), all post requests will be converted into get requests.

json: Return JSON data.

jsonp: JSONP format. When calling a function using the SONP form, such as myurl?callback=?, JQuery will automatically replace the last "?" with the correct function name to execute the callback function.

three. Mime data type and response's setContentType() method

What is a MIME type? When transmitting the output results to the browser, the browser must start the appropriate application to handle this Output document. This can be accomplished through various types of MIME (Multipurpose Internet Mail Extensions). In HTTP, MIME types are defined in the Content-Type header.

For example, suppose you want to send a Microsoft Excel file to the client. Then the MIME type at this time is "application/vnd.ms-excel". In most practical cases, this file will then be passed to Execl for processing (assuming that we configure Execl to handle the specific MIME type application). In Java, the way to set the MIME type is through the ContentType property of the Response object. For example, commonly used: response.setContentType("text/html;charset=UTF-8") to set.

In the earliest HTTP protocol, there was no additional data type information. All transmitted data were interpreted by the client program as Hypertext Markup Language HTML documents. In order to support multimedia data types, the HTTP protocol used MIME data type information appended to the front of the document to identify the data type.

Each MIME type consists of two parts. The first part is the general category of data, such as text, image, etc., and the second part defines the specific type.

Common MIME types:

Hypertext Markup Language text.html,.html text/html

Normal text.txt text/plain

RTF text.rtf application/rtf

GIF graphics.gif image/gif

JPEG graphics.ipeg,.jpg image/jpeg

au sound file .au audio/basic

MIDI music file mid,.midi audio/midi,audio/x-midi

RealAudio music file .ra, .ram audio/x-pn-realaudio

MPEG file.mpg,.mpeg video/mpeg

AVI file.avi video/x-msvideo

GZIP file.gz application/x-gzip

TAR File.tar application/x-tar

When the client program receives data from the server, it only accepts the data stream from the server and does not know the name of the document, so the server must use additional information to tell the client program the data MIME type.

Before the server sends the real data, it must first send the MIME type information that marks the data. This information is defined using the Content-type keyword. For example, for an HTML document, the server will first send the following two lines of MIME Identification information, this identification is not really part of the data file.

Content-type: text/html

Note that the second line is a blank line, which is necessary. The purpose of using this blank line is to separate the MIME information from the real data content. open.

As mentioned earlier, in Java, the way to set the MIME type is through the ContentType property of the Response object. The setting method is to use the response.setContentType(MIME) statement. The function of response.setContentType(MIME) It enables the client browser to distinguish different types of data and call different program embedded modules in the browser according to different MIMEs to process the corresponding data.

A large number of MIME types are defined in Tomcat’s installation directory \conf\web.xml, which you can refer to. For example, you can set:

response.setContentType("text/html; charset=utf-8"); html

response.setContentType("text/plain; charset=utf-8") ; Text

application/json json data

This method sets the content type of the response sent to the client. The response has not yet been submitted. The content type given can include character encoding specifications, for example: text/html;charset=UTF-8. If this method is called before the getWriter() method is called, then the character encoding of the response will only be set from the given content type. If this method is called after the getWriter() method is called or after it is submitted, it will not set the character encoding of the response. In the case of using the http protocol, this method sets the Content-type entity header.

Four. Three ways to obtain json data using the $.ajax() method

The configuration of the dataType parameter determines how jquery helps us automatically parse the data returned by the server. There are several ways to obtain the background The returned json string is parsed into a json object. The following is Java as an example. The results of the following three methods are shown in Figure 1. The project is running on the intranet and cannot take screenshots. It can only take photos. Please forgive me.

1. If the dataType is not set in the $.ajax() parameter, and the return type is not set in the background response, it will be processed as ordinary text by default [response.setContentType("text /html;charset=utf-8"); is also processed as text]. In js, you need to manually use eval() or $.parseJSON() and other methods to convert the returned string into a json object for use.

//Java代码:后台获取单个数控定位器的历史表格的数据
	public void getHistorySingleData() throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String deviceName = request.getParameter("deviceName");
		String startDate= request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		SingleHistoryData[] singleHistoryData = chartService.getHistorySingleData(deviceName,startDate, endDate);
		System.out.println(singleHistoryData.length);
		System.out.println(JSONArray.fromObject(singleHistoryData).toString());//打印:[{"time":"2016-11-11 10:00:00","state":"运行","ball":"锁紧",....},{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....},{},{}....]查到几条singleHistoryData对象就打印几个对象的信息{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....}
		response.getWriter().print(JSONArray.fromObject(singleHistoryData).toString());
	}
	/*js代码:选择查询某一时间段的数据,点击查询之后进行显示*/
 $("#search").click(function () {
 	var data1 = [];
 	var n;
 	var deviceName=$("body").attr("id"); 
  var startDate = $("#startDate").val();
  var endDate = $("#endDate").val();
  $.ajax({
   url:"/avvii/chart/getHistorySingleData",
   type:"post",
   data:{
    "deviceName":deviceName,
    "startDate": startDate,
    "endDate": endDate
   },
   success: function (data) {
  	 alert(data);//---->弹出[{"time":"2016-11-11 10:00:00","state":"运行","ball":"锁紧",....},{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....},{},{}....],后台传过来几条singleHistoryData对象就打印几个对象的信息{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....}
 		 alert(Object.prototype.toString.call(data)); //--->弹出[object String],说明获取的是String类型的数据
  	 var JsonObjs = eval("(" + data + ")");  //或者:var JsonObjs = $.parseJSON(data);
 		 alert(JsonObjs);//alert(JsonObjs);---->弹出[object Object],[object Object],[object Object][object Object],[object Object],[object Object]……后台传过来几条singleHistoryData对象就打印几个[object Object]
    n=JsonObjs.length;
    if(n==0){
   	 alert("您选择的时间段无数据,请重新查询");
    }
 		 for(var i = 0; i 

2. Set dataType="json" in the $.ajax() parameter, then jquery will automatically convert the returned string into a json object. The background can be set to: [Recommended] response.setContentType("text/html;charset=utf-8"); or response.setContentType("application/json;charset=utf-8");

	//Java代码:后台获取单个数控定位器的历史表格的数据
	public void getHistorySingleData() throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String deviceName = request.getParameter("deviceName");
		String startDate= request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		SingleHistoryData[] singleHistoryData = chartService.getHistorySingleData(deviceName,startDate, endDate);
		System.out.println(singleHistoryData.length);
		System.out.println(JSONArray.fromObject(singleHistoryData).toString());//打印:[{"time":"2016-11-11 10:00:00","state":"运行","ball":"锁紧",....},{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....},{},{}....]查到几条singleHistoryData对象就打印几个对象的信息{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....}
		response.getWriter().print(JSONArray.fromObject(singleHistoryData).toString());
	}
/*js代码:页面首次加载时,显示规定时间段的数据*/ 
	var data1 = [];
	var deviceName=$("body").attr("id"); 
 var startDate = $("#startDate").val("2000-01-01 00:00:00");
 var endDate = $("#endDate").val("2018-01-01 00:00:00");
 $.ajax({
  url:"/avvii/chart/getHistorySingleData",
  type:"post",
  data:{
   "deviceName":deviceName,
   "startDate": "2000-01-01 00:00:00",
   "endDate": "2018-01-01 00:00:00"
  },
  dataType:"json",
  success: function (data) {
 	 alert(data);//---->弹出[object Object],[object Object],[object Object][object Object],[object Object],[object Object]……后台传过来几条singleHistoryData对象就打印几个json对象:[object Object]
   for(var i = 0; i <p style="text-align: left;"> 3. DataType is not specified in the ajax method parameters, and the return type is set to "application/json" in the background. In this way, jquery will intelligently judge based on the mime type and automatically parse it into a json object. </p><pre class="brush:php;toolbar:false">
	//Java代码:后台获取单个数控定位器的历史表格的数据
	public void getHistorySingleData() throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setContentType("application/json;charset=utf-8");
		String deviceName = request.getParameter("deviceName");
		String startDate= request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		SingleHistoryData[] singleHistoryData = chartService.getHistorySingleData(deviceName,startDate, endDate);
		System.out.println(singleHistoryData.length);
		System.out.println(JSONArray.fromObject(singleHistoryData).toString());//打印:[{"time":"2016-11-11 10:00:00","state":"运行","ball":"锁紧",....},{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....},{},{}....]查到几条singleHistoryData对象就打印几个对象的信息{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....}
		response.getWriter().print(JSONArray.fromObject(singleHistoryData).toString());
	}
 /*js代码:页面首次加载时,显示规定时间段的数据*/ 
	var data1 = [];
	var deviceName=$("body").attr("id"); 
 var startDate = $("#startDate").val("2000-01-01 00:00:00");
 var endDate = $("#endDate").val("2018-01-01 00:00:00");
 $.ajax({
  url:"/avvii/chart/getHistorySingleData",
  type:"post",
  data:{
   "deviceName":deviceName,
   "startDate": "2000-01-01 00:00:00",
   "endDate": "2018-01-01 00:00:00"
  },
  success: function (data) {
 	 alert(data);//---->弹出[object Object],[object Object],[object Object][object Object],[object Object],[object Object]……后台传过来几条singleHistoryData对象就打印几个json对象:[object Object]
   for(var i = 0; i <p style="text-align: left;">Note: As long as there is a setting to return a json object in the foreground or background, there is no need to use the eval() method or $.parseJSON() method to parse, and an error will occur if you parse again. </p><p style="text-align: left;"><span style="background-color: #ccffcc">Summary: Among the above methods, it is recommended to use the second method, which is convenient and less error-prone. </span></p><p style="text-align: left;"><span style="color: #ff0000"><strong>five. eval() method</strong></span></p><p style="text-align: left;">var json object=eval('('+json data+')'); The content enclosed in curly brackets is returned after being executed by eval() JSON object. </p><p style="text-align: left;">How the eval function works: The eval function evaluates a given string containing JavaScript code and attempts to execute the expression or a series of legal JavaScript statements contained in the string. The eval function will return the value or reference contained in the last expression or statement. </p><p style="text-align: left;"><span style="color: #ff00ff"><strong> Why do we need to add "("("+data+")");//" to eval? </strong></span></p><p style="text-align: left;"><strong>The reason is: </strong>eval itself. Since json starts and ends with "{}", it will be processed as a statement block in JS, so it must be forced to be converted into an expression. The purpose of adding parentheses is to force the eval function to convert the expression in the parentheses into an object when processing JavaScript code, rather than executing it as a statement. For example, take the object literal {}. If no outer brackets are added, then eval will recognize the braces as the beginning and end marks of the JavaScript code block, and {} will be considered to execute an empty statement. </p><p style="text-align: left;">The above summary of several ways to obtain json data from the server based on the $.ajax() method is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the script. s home. </p><p> I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! </p><p>Recommended reading: </p><p><a href="http://www.php.cn/js-tutorial-388558.html" target="_blank">jquery+css3 to create navigation for the live broadcast platform</a></p><p><a href="http://www.php.cn/js-tutorial-388554.html" target="_blank">How to achieve the mouse response buffer animation effect? </a><br></p><p><a href="http://www.php.cn/js-tutorial-388547.html" target="_blank">How to automatically load more content when the scroll bar slides to the bottom</a></p><p><a href="http://www.php.cn/js-tutorial-388538.html" target="_blank">How to add li tags and attributes with jQuery</a><br></p>

The above is the detailed content of How $.ajax() gets json data from the server. For more information, please follow other related articles on 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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor