Home Web Front-end JS Tutorial How to get json data from the server using the $.ajax() method

How to get json data from the server using the $.ajax() method

Apr 13, 2018 am 09:38 AM
javascript server

This time I will show you how to get json data from the server using the $.ajax() method. What are the precautions for using the $.ajax() method to get json data from the server? The following is a practical case, let’s take a look.

one. What is json

json is a data structure that replaces xml. Compared with xml, it is smaller but has strong descriptive capabilities. It uses less traffic and is faster to transmit data over the network.

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

{key-value pair}: json object

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

"": The attribute or value within double quotes is

:: 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} It can be understood as 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, which is 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: Returns 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 setContentType() method

What are MIME types? When transmitting output results to the browser, the browser must start the appropriate application to process the 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 client. Then the MIME type at this time is "application/vnd.ms-excel". In most practical cases, this file will then be transferred to Execl to handle (assuming we set Execl to handle special MIME types of applications). 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 was interpreted by the client program as a Hypertext Markup Language HTML document. In order to support multimedia data types, the HTTP protocol used MIME appended before the document. Data type information 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

Plain 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 files mid,.midi audio/midi,audio/x-midi

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

MPEG files .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 MIME type of the data.

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 does not 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.

As mentioned earlier, in Java, the way to set the MIME type is through the ContentType attribute of the Response object. The setting method is to use the response.setContentType(MIME) statement. The function of response.setContentType(MIME) is to make the client browser , 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 confweb.xml, the installation directory of Tomcat, for reference. 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 before the response is 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 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 json string returned by the background and parse it into a json object. The following is an example of Java explaining the results of the following three methods

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());
	}
Copy after login
rrree

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

	/*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 < JsonObjs.length; i++){	      
		  	  var name = JsonObjs[i][&#39;time&#39;];//针对每一条数据:JsonObjs[i],或者:JsonObjs[i].time
		 	  var state = JsonObjs[i][&#39;state&#39;];
		 	  var ball = JsonObjs[i][&#39;ball&#39;];
		 	  var xd = JsonObjs[i][&#39;xd&#39;];
		 	  var yd = JsonObjs[i][&#39;yd&#39;];
		 	  var zd = JsonObjs[i][&#39;zd&#39;];
		 	  var xf = JsonObjs[i][&#39;xf&#39;];
		 	  var yf = JsonObjs[i][&#39;yf&#39;];
		 	  var zf = JsonObjs[i][&#39;zf&#39;];
      data1[i] = {name:name,state:state,ball:ball,xd:xd,yd:yd,zd:zd,xf:xf,yf:yf,zf:zf};//个数与下面表头对应起来就可以了,至于叫什么名字并不影响控件的使用
    }
 		 if(JsonObjs.length != 10){
 			 for(var j=0;j<(10-((JsonObjs.length)%10));j++){    //补全最后一页的空白行,使表格的长度保持不变
 				 data1[j+JsonObjs.length] = {name:" ",state:"",ball:"",xd:"",yd:"",zd:"",xf:"",yf:"",zf:""}; 
 			 }
 		 }
    var userOptions = {
      "id":"kingTable",        				//必须 表格id
      "head":["时间","运行状态","球头状态","X向位置/mm","Y向位置/mm","Z向位置/mm","X向承载力/Kg","Y向承载力/Kg","Z向承载力/Kg"], //必须 thead表头
      "body":data1,         				//必须 tbody 后台返回的数据展示
      "foot":true,         					// true/false 是否显示tfoot --- 默认false
      "displayNum": 10,        					//必须 默认 10 每页显示行数
      "groupDataNum":6,        					//可选 默认 10 组数
      sort:false,         					// 点击表头是否排序 true/false --- 默认false
      search:false,         					// 默认为false 没有搜索
      lang:{
       gopageButtonSearchText:"搜索"
      }
    }
    var cs = new KingTable(null,userOptions);
   }
  }); 
 });
Copy after login
	//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());
	}
Copy after login

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.

/*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 < data.length; i++){	      
	  	  var name = data[i]['time'];
	 	  var state = data[i]['state'];
	 	  var ball = data[i]['ball'];
	 	  var xd = data[i]['xd'];
	 	  var yd = data[i]['yd'];
	 	  var zd = data[i]['zd'];
	 	  var xf = data[i]['xf'];
	 	  var yf = data[i]['yf'];
	 	  var zf = data[i]['zf'];
     data1[i] = {name:name,state:state,ball:ball,xd:xd,yd:yd,zd:zd,xf:xf,yf:yf,zf:zf};
   }
		 if(data.length != 10){
			 for(var j=0;j<(10-((data.length)%10));j++){    //补全最后一页的空白行,使表格的长度保持不变
				 data1[j+data.length] = {name:" ",state:"",ball:"",xd:"",yd:"",zd:"",xf:"",yf:"",zf:""}; 
			 }
		 }
   var userOptions = {
     "id":"kingTable",        				//必须 表格id
     "head":["时间","运行状态","球头状态","X向位置/mm","Y向位置/mm","Z向位置/mm","X向承载力/Kg","Y向承载力/Kg","Z向承载力/Kg"], //必须 thead表头
     "body":data1,         				//必须 tbody 后台返回的数据展示
     "foot":true,         					// true/false 是否显示tfoot --- 默认false
     "displayNum": 10,        					//必须 默认 10 每页显示行数
     "groupDataNum":6,        					//可选 默认 10 组数
     sort:false,         					// 点击表头是否排序 true/false --- 默认false
     search:false,         					// 默认为false 没有搜索
     lang:{
      gopageButtonSearchText:"搜索"
     }
   }
   var cs = new KingTable(null,userOptions);
  }
 });
Copy after login
rrree

Note: As long as there is a setting to return a json object in the front or backend, there is no need to use the eval() method or $.parseJSON() method to parse, otherwise an error will occur when parsing again.

Summary: Among the above methods, it is recommended to use the second method, which is convenient and less error-prone.

five. eval() method

var json object=eval('(' json data ')'); A JSON object is returned after the content enclosed in curly brackets is executed by eval().

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.

Why do we need to add "("(" data ")");//" to eval?

The reason is: 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.

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!

Recommended reading:

getBoundingClientRect usage and compatibility processing

detailed explanation of vue's implementation of the small ball parabolic effect of the shopping cart

Detailed explanation of the use of components in Vue.js

The above is the detailed content of How to get json data from the server using the $.ajax() method. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 problem that eMule search cannot connect to the server How to solve the problem that eMule search cannot connect to the server Jan 25, 2024 pm 02:45 PM

Solution: 1. Check the eMule settings to make sure you have entered the correct server address and port number; 2. Check the network connection, make sure the computer is connected to the Internet, and reset the router; 3. Check whether the server is online. If your settings are If there is no problem with the network connection, you need to check whether the server is online; 4. Update the eMule version, visit the eMule official website, and download the latest version of the eMule software; 5. Seek help.

Solution to the inability to connect to the RPC server and the inability to enter the desktop Solution to the inability to connect to the RPC server and the inability to enter the desktop Feb 18, 2024 am 10:34 AM

What should I do if the RPC server is unavailable and cannot be accessed on the desktop? In recent years, computers and the Internet have penetrated into every corner of our lives. As a technology for centralized computing and resource sharing, Remote Procedure Call (RPC) plays a vital role in network communication. However, sometimes we may encounter a situation where the RPC server is unavailable, resulting in the inability to enter the desktop. This article will describe some of the possible causes of this problem and provide solutions. First, we need to understand why the RPC server is unavailable. RPC server is a

Detailed explanation of CentOS installation fuse and CentOS installation server Detailed explanation of CentOS installation fuse and CentOS installation server Feb 13, 2024 pm 08:40 PM

As a LINUX user, we often need to install various software and servers on CentOS. This article will introduce in detail how to install fuse and set up a server on CentOS to help you complete the related operations smoothly. CentOS installation fuseFuse is a user space file system framework that allows unprivileged users to access and operate the file system through a customized file system. Installing fuse on CentOS is very simple, just follow the following steps: 1. Open the terminal and Log in as root user. 2. Use the following command to install the fuse package: ```yuminstallfuse3. Confirm the prompts during the installation process and enter `y` to continue. 4. Installation completed

How to configure Dnsmasq as a DHCP relay server How to configure Dnsmasq as a DHCP relay server Mar 21, 2024 am 08:50 AM

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

Best Practice Guide for Building IP Proxy Servers with PHP Best Practice Guide for Building IP Proxy Servers with PHP Mar 11, 2024 am 08:36 AM

In network data transmission, IP proxy servers play an important role, helping users hide their real IP addresses, protect privacy, and improve access speeds. In this article, we will introduce the best practice guide on how to build an IP proxy server with PHP and provide specific code examples. What is an IP proxy server? An IP proxy server is an intermediate server located between the user and the target server. It acts as a transfer station between the user and the target server, forwarding the user's requests and responses. By using an IP proxy server

What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline Mar 13, 2024 pm 04:40 PM

What should I do if I can’t enter the game when the epic server is offline? This problem must have been encountered by many friends. When this prompt appears, the genuine game cannot be started. This problem is usually caused by interference from the network and security software. So how should it be solved? The editor of this issue will explain I would like to share the solution with you, I hope today’s software tutorial can help you solve the problem. What to do if the epic server cannot enter the game when it is offline: 1. It may be interfered by security software. Close the game platform and security software and then restart. 2. The second is that the network fluctuates too much. Try restarting the router to see if it works. If the conditions are OK, you can try to use the 5g mobile network to operate. 3. Then there may be more

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to install PHP FFmpeg extension on server? How to install PHP FFmpeg extension on server? Mar 28, 2024 pm 02:39 PM

How to install PHPFFmpeg extension on server? Installing the PHPFFmpeg extension on the server can help us process audio and video files in PHP projects and implement functions such as encoding, decoding, editing, and processing of audio and video files. This article will introduce how to install the PHPFFmpeg extension on the server, as well as specific code examples. First, we need to ensure that PHP and FFmpeg are installed on the server. If FFmpeg is not installed, you can follow the steps below to install FFmpe

See all articles