jquery uses Ajax to manipulate JSON format data description

Source: Internet
Author: User
Tags error code http authentication http request

JSON (JavaScript Object notation) is a lightweight data interchange format. JSON stores data that is structured as "key-value." Sometimes we need to read JSON-formatted data files, which can be implemented in jquery using Ajax or $.getjson () methods.

First look at the introduction to $.ajax () in the API


Jquery.ajax (Url,[settings])
Overview
Load remote data through an HTTP request.

JQuery bottom AJAX implementation. Simple and easy-to-use high-level implementation see $.get, $.post, etc. $.ajax () returns the XMLHttpRequest object that it created. Most of the time you don't have to manipulate the function directly, unless you need to manipulate the infrequently used options for more flexibility.

In the simplest case, $.ajax () can be used directly without any parameters.

Note that all options can be set globally through the $.ajaxsetup () function.

callback function

If you want to process data from $.ajax (), you need to use a callback function. Beforesend, error, Datafilter, success, complete.

Beforesend is invoked before the request is sent, and a xmlhttprequest is passed in as an argument.
The error is invoked when an error is requested. Incoming XMLHttpRequest object, describing the type of error string and an exception object (if any)
Datafilter is invoked after the request succeeds. Incoming data returned and the value of the "DataType" parameter. and must return the new data (possibly processed) to the success callback function.
Success called after the request. Incoming data returned, and a string containing the success code.
Complete calls this function after the request completes, either successfully or unsuccessfully. The incoming XMLHttpRequest object, and a string containing the success or error code.
Data type

The $.ajax () function relies on the information provided by the server to process the returned data. If the server reports that the returned data is XML, the returned results can be traversed using a normal XML method or a jquery selector. If you see other types, such as HTML, the data is treated as text.

You can also specify different data processing methods through the DataType option. In addition to simple XML, you can also specify HTML, JSON, JSONP, script, or text.

Where the data returned by the text and XML types is not processed. The data simply passes the XMLHttpRequest responsetext or responsehtml attribute to the success callback function,

' Note ', we must make sure that the MIME type reported by the Web server is matched with the datatype we choose. For example, XML, the server side must declare Text/xml or application/xml to achieve consistent results.

If you specify an HTML type, any embedded JavaScript executes before the HTML is returned as a string. Similarly, if you specify a script type, the server-side generated JavaScript is executed first, and then the script is returned as a text data.

If specified as a JSON type, the acquired data is parsed as a JavaScript object and the constructed object is returned as the result. To achieve this, he first tried to use Json.parse (). If the browser does not support it, use a function to build it. JSON data is a structured data that can be easily parsed by JavaScript. If you get a data file that resides on a remote server (the domain name is different, that is, you get the data across the domain), you need to use the JSONP type. Using this type, a query string parameter is created callback=? , this parameter is appended to the URL of the request. The server side should precede the JSON data with the callback function name in order to complete a valid JSONP request. If you want to specify the parameter name of the callback function to replace the default callback, you can set the JSONP parameter of the $.ajax ().

Note that Jsonp is an extension of the JSON format. He asked for some server-side code to detect and process query string parameters. See the original article for more information.

If you specify a script or JSONP type, then when you receive data from the server, you are actually using the <script> tag instead of the XMLHttpRequest object. In this case, $.ajax () no longer returns a XMLHttpRequest object, and the event handler function, such as beforesend, is not passed.

Sending data to a server

By default, the AJAX request uses the Get method. If you want to use the Post method, you can set the type parameter value. This option also affects how the contents of the data option are sent to the server.

The data option can contain either a query string, such as key1=value1&key2=value2, or a map, such as {key1: ' value1 ', Key2: ' value2 '}. If the latter form is used, the data dispatcher is converted to a query string. This process can also be avoided by setting the ProcessData option to false. This process may not be appropriate if we want to send an XML object to the server. And in this case, we should also change the value of the ContentType option and replace the default application/x-www-form-urlencoded with other appropriate MIME types.

Advanced options

The global option is used to block responses to registered callback functions, such as. Ajaxsend, or Ajaxerror, and similar methods. This can be useful in some cases, such as sending a request that is very frequent and short, and disabling this in Ajaxsend. For more information about these methods, see below.

If the server requires HTTP authentication, the user name and password can be set by using the username and password options.

Ajax requests are time-limited, so the error warning is captured and processed to enhance the user experience. The parameter of the request timeout usually retains its default value, or it is set globally by Jquery.ajaxsetup, and the timeout option is rarely reset for a particular request.

By default, the request is always sent out, but it is possible for the browser to fetch the data from his cache. To prevent the use of cached results, you can set the cache parameter to False. You can set Ifmodified to True if you want to determine whether the data has been reported as an error since the last request has not changed.

Scriptcharset allows a specific set of character sets for <script> tag requests to be used for script or jsonp similar data. This is especially useful when scripts and page character sets are not the same.

The first letter of Ajax is the asynchronous letter, which means that all operations are parallel and the order of completion is not related. The async parameter of $.ajax () is always set to true, which indicates that other code can still be executed after the request has started. It is strongly not recommended to set this option to false, which means that all requests are no longer asynchronous, which can also cause the browser to be locked.

The $.ajax function returns the XMLHttpRequest object that he created. jquery usually handles and creates the object internally, but the user can also pass a XHR object created by the XHR option. The returned object is usually discarded, but still provides a low-level interface to observe and manipulate the request. For example, the. Abort () on the calling object can suspend the request until the request completes.


Here's how to parse Songs.json using jquery.

This is Songs.json file content

Song.json XHTML
[
{"Optionkey": "1", "OptionValue": "Canon in D"},
{"Optionkey": "2", "OptionValue": "Wind Song"},
{"Optionkey": "3", "OptionValue": "Wings"}
]

My HTML code:

Html-json XHTML

The code is as follows Copy Code

<div> Click on the button to get JSON data </div>
<input type= "button" id= "button" value= "OK"/>
<div id= "Result" ></div>

jquery code to get JSON data using Ajax:

The code is as follows Copy Code

Js-json JavaScript
$ (document). Ready (function () {
$ (' #button '). Click (function () {
$.ajax ({
Type: "Get",
URL: "Songs.json",
DataType: "JSON",
Success:function (data) {
var song= "<ul>";
I represents the index position in data, N represents an object containing information
$.each (Data,function (i,n) {
Gets the value of the property in the object that is Optionsvalue
song+= "<li>" +n["OptionValue"]+ "</li>";
});
song+= "</ul>";
$ (' #result '). Append (song);
}
});
return false;
});
});


API for Jquery.getjson


Jquery.getjson (URL, [data], [callback])
Overview
Load JSON data through an HTTP GET request.

In JQuery 1.2, you can load JSON data for other domains, such as "myurl?callback=?", by using a callback function in JSONP form. Will jQuery be replaced automatically? To the correct function name to execute the callback function. Note: The code after this line will execute before the callback function executes.

Parameters
url,[data],[callback]string,map,functionv1.0
URL: Sends the request address.

Data: Key/value parameter to be sent.

Callback: callback function when load succeeds.


It's a much simpler implementation.

  code is as follows copy code


$ (document . Ready (function () {
 $ (' #button '). Click (function () {
  $.getjson (' Songs.json ', function ( Data) {
   var song= "<ul>";
   $.each (Data,function (i,n) {
     song+= "<li>" +n["OptionValue"]+ "</li>";
   });
   music+= "</ul>";
   $ (' #result '). Append (song);
  });
  return false;
 });
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.