About how to get json data from the server in the $.ajax() method
Below I 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.
one. What is json
json is a data structure that replaces xml. Compared with xml, it is smaller but has strong description ability. 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 a basic data type, an array or an object), so {"age": 18} can be understood as a value containing age. 18 json object, 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 a 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 automatically cached. 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 special MIME types). 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 big 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 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 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 before, 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|
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");
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
|
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
|
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.
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')'); The content enclosed in curly brackets is returned by eval() after being executed. A JSON object is returned .
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.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
JavaScript recursive traversal and non-recursive traversal
How to use the Upload upload component of element-ui in vue
How to implement calling between methods in vue
The above is the detailed content of About how to get json data from the server in the $.ajax() method. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

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.

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

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

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

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

Google Authenticator is a tool used to protect the security of user accounts, and its key is important information used to generate dynamic verification codes. If you forget the key of Google Authenticator and can only verify it through the security code, then the editor of this website will bring you a detailed introduction on where to get the Google security code. I hope it can help you. If you want to know more Users please continue reading below! First open the phone settings and enter the settings page. Scroll down the page and find Google. Go to the Google page and click on Google Account. Enter the account page and click View under the verification code. Enter your password or use your fingerprint to verify your identity. Obtain a Google security code and use the security code to verify your Google identity.

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

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
