Jquery $. Get of $. Post of $. Ajax of $. GetJSON of usage summary

  • 2020-03-29 23:44:20
  • OfStack

Detailed interpretation of Jquery Ajax functions:
$.get (), $. Post (), $. Ajax (), $. GetJSON ()

A, $.get (url, [data], [callback])

Url is the request address, data is the list of request data, callback is the callback function after the request is successful, the function accepts two parameters, the first parameter is the data returned by the server, the second parameter is the state of the server, is an optional parameter.

The format of the data returned by the server is actually a string situation, not the json data format we want, and the reference here is just for comparison

$.get("data.php",$("#firstName.val()"),function(data){ $("#getResponse").html(data); }//The data returned is of type string );

Second, $.post (url, [data], [callback], [type])

This function is similar to the $.get() parameter, plus a type parameter, type is the data type of the request, can be HTML, XML,json and other types, if we set this parameter as: json, then the format of the return is json format, if not set, and $.get() return format is the same as the string

$.post("data.php",$("#firstName.val()"),function(data){ $("#postResponse").html(data.name); },"json"//Set the type of the retrieved data, so the resulting data format is of type json );

Three, $. Ajax (opiton)

$. Ajax () this function is powerful, you can do a lot of precise control of ajax, need to elaborate please refer to the relevant information

$.ajax({ url: "ajax/ajax_selectPicType.aspx", data:{Full:"fu"}, type: "POST", dataType:'json', success:CallBack, error:function(er){ BackErr(er);} });

Four, $. GetJSON (url, [data], [callback])

$.getJSON("data.php",$("#firstName.val()"),function(jsonData){ $("#getJSONResponse").html(jsonData.id);}//Without setting, the data type directly obtained is json,
So you need to use it when you call it jsonData.id way );

There are more and more ajax-based applications out there, and it's not pleasant for the front-end developer to deal directly with the underlying HTTPRequest. Since jQuery encapsulates JavaScript, you've certainly thought about AJAX applications. Indeed, it's N times easier to write AJAX with jQuery than with JS. (I do not know with jQuery long, will you lose the knowledge of JS......) Assuming that you are already familiar with jQuery syntax, let's summarize some of the ajax applications.

Loading static pages

Load (url, [data], [callback]);
Url (String) the url address of the requested HTML page
Data (Map)(optional parameter) is the key/value data sent to the server
Callback (optional parameter) for when the request completes (it does not need to be a success)

The load() method makes it easy to load static page content into a specified jQuery object.


In this way, the content of data.html is loaded into the DOM object with an ajax-div ID. You can even implement Ajax operations to load parts of the content by specifying an ID, such as:


Implement the GET and POST methods

Get (url, [data], [callback])
Url (String) sends the url address of the request.
Data (Map)(optional parameter) the data to be sent to the server, represented as a key-value pair of Key/value, is appended to the request URL as a QueryString
Callback (optional parameter) is called when the callback function loads successfully (only if the Response returns a success)

This is obviously a function that implements the GET method and is fairly simple to use

$.get('login.php', {
   id      : 'Robin',
   password: '123456',
   gate    : 'index'
  }, function(data, status) {
   //Data is the return object and status is the status of the request
   //At this point, suppose the server script returns a text "hello Robin!" , < br / > The browser will pop up a dialog box showing the text
   //The result is success, error, and so on, but here's the function
that runs on success   });

Post (url, [data], [callback], [type])

Url (String) sends the url address of the request.
Data (Map)(optional parameter) the data to be sent to the server, expressed as a key-value pair of Key/value
Callback (optional parameter) is called when the callback function loads successfully (only if the Response returns a success)
Type (String) (optional parameter) request data type, XML,text,json, etc

JQuery is also a simple function, in fact, the use

$.post('regsiter.php', {
   password: '123456',
  },function(data, status) {
  }, "json");

Event-driven script loading function: getScript()

GetScript (url, callback)
Url (String) to load the JS file address
Callback (Function) (optional) is successfully loaded

The getScript() function can load a JavaScript script remotely and execute it. This function loads JS files across domains (magic... ? !). . The significance of this function is huge, it can greatly reduce the amount of code that the page first loads, because you can load the corresponding JS file based on the user's interaction, without having to load it all when the page initializes.

$.getScript('ajaxEvent.js', function() {
   alert("Scripts Loaded!");
   //Load ajaxevent.js and display a dialog after a successful load. < br / >   });

Building a bridge for data communication: getJSON()

GetJSON (url, [data], [callback])
The url (String) sends the request address
Data (Map) (optional) to be sent as Key/value parameter
The callback (Function) (optional) loads successfully.

JSON is an ideal data transfer format that is well integrated with JavaScript or other host languages and can be used directly by JS. Using JSON is structurally more reasonable and safer than sending "naked" data directly through GET and POST. As for jQuery's getJSON() function, it's just a simplified version of the ajax() function that sets the JSON parameters. This function can also be used across domains and has some advantages over get() and post(). In addition, this function can be written by writing the request url as "myurl? "Callback =X", which causes the program to execute the callback function X.

   request: images,
   id:      001,
   size:    large
   }, function(json) {
    //Here json is the json object returned remotely, assuming the format is
    //{'images' : [
    // {link: images/001.jpg, x :100, y : 100},
    // {link: images/002.jpg, x : 200, y 200:}

The lower level ajax() function
While the get() and post() functions are simple and easy to use, they still don't meet some of the more complex design requirements, such as doing different things at different times during an ajax send. JQuery provides a more specific function: ajax().

Ajax (options)
Ajax () provides a large number of parameters, so you can implement fairly complex functionality.

Parameter names type describe
url String ( The default : Current page address ) The address at which the request was sent.
type String ( The default : " GET " ) Request way ( " POST " or " GET " ) . The default is " GET ".
Note: others HTTP Request methods, such as PUT and DELETE It is also available, but only partially supported by browsers.
timeout Number Set the request timeout in milliseconds. This setting overrides the global Settings.
async Boolean ( The default : true) By default, all requests are asynchronous.
If you need to send a synchronization request, set this option to false .
Note that the synchronous request locks the browser and the user must wait for the request to complete before any other actions can be performed.
beforeSend Function Can be modified before sending the request XMLHttpRequest Object, such as add custom HTTP Head.

XMLHttpRequest The object is the only parameter.

function (XMLHttpRequest) { this; // the options for this ajax request } function (XMLHttpRequest) { this; // the options for this ajax request }

cache Boolean ( The default : true) jQuery 1.2 New function, set as false The request information will not be loaded from the browser cache.
complete Function The callback function after the request completes ( Called when a request succeeds or fails ) .

Parameters: XMLHttpRequest Object, a success message string.

function (XMLHttpRequest, textStatus) { this; // the options for this ajax request } function (XMLHttpRequest, textStatus) { this; // the options for this ajax request }
contentType String ( The default : " application/x-www-form-urlencoded " ) Content encoding type when sending information to server. The default values are appropriate for most applications.
data Object,
Data sent to the server. Automatically converts to the request string format. GET The request will be appended to URL After.
To view processData Option to disable this automatic conversion. Must be Key/Value Format.
If it's an array, jQuery Different values will automatically correspond to the same name.
Such as {foo:["bar1", "bar2"]} convert ' &foo=bar1&foo=bar2 '.
dataType String The type of data expected to be returned by the server. If you don't specify, jQuery Will automatically be based on HTTP package MIME information
return responseXML or responseText , and passed as arguments to the callback function :

" xml " : return XML Documentation, available jQuery To deal with.

" html " : Return plain text HTML Information; contains script Elements.

" script " : Return plain text JavaScript The code. The results are not automatically cached.

" json " : return JSON data .

" jsonp " : JSONP Format. use JSONP When the form calls a function,

Such as " myurl?callback=? " jQuery Will automatically replace ? Is the correct function name to execute the callback function.

error Function ( The default : Automatic judgment (xml or html)) This method is called when the request fails.

This method has three parameters: XMLHttpRequest Object, error message, error object caught (possibly).

function (XMLHttpRequest, textStatus, errorThrown) { // normally textStatus and errorThown Only one of them has a value this; // the options for this ajax request } function (XMLHttpRequest, textStatus, errorThrown) { // normally textStatus and errorThown Only one of them has a value this; // the options for this ajax request }
global Boolean ( The default : true) Whether to trigger global AJAX Events. Set to false Global will not be triggered AJAX The event,

Such as ajaxStart or ajaxStop . Can be used to control different Ajax The event

ifModified Boolean ( The default : false) Gets new data only when server data changes.

use HTTP package Last-Modified Header information judgment.

processData Boolean ( The default : true) By default, the data sent is converted into an object ( It's not technically a string )

To match the default content type " application/x-www-form-urlencoded ".

If you want to send DOM For tree information or other information that you do not want to convert, set to false .

success Function

Callback function after successful request. This method takes two arguments: the server returns data and returns status

function (data, textStatus) { // data could be xmlDoc, jsonObj, html, text, etc... this; // the options for this ajax request } function (data, textStatus) { // data could be xmlDoc, jsonObj, html, text, etc... this; // the options for this ajax request }

You can specify XML, script, HTML, json as their data types, you can set handlers for the states beforeSend, error, sucess, complete, etc., and many other parameters can be used to completely define the user's Ajax experience. In the following example, we use ajax() to invoke an XML document:

    url: 'doc.xml',
    type: 'GET',
    dataType: 'xml',
    timeout: 1000,
    error: function(){
        alert('Error loading XML document');
    success: function(xml){
  //XML is the jQuery object for XML, where you can find nodes using find(), next(), or XPath,
And the use jQuery operation HTML Objects don't make a difference

Learn more about AJAX events
Some of the methods discussed earlier have their own event handling mechanisms, and as a whole, the page is only a local function. JQuery provides the definition of AJAX global functions to meet special needs. Here are all the functions provided by jQuery (in order of triggering) :

(global event) starts a new Ajax request, and there are no other Ajax requests in progress at this time
Triggered when an Ajax request starts. If necessary, you can set up the XMLHttpRequest object here
(global event) a global event that is fired before the request starts
Triggered when the request succeeds. That is, the server did not return an error and the returned data did not return an error
Global event global request successful
The error
(local event) is triggered only when an error occurs. You cannot execute both success and error callbacks at the same time
Global event global occurs when an error occurs
(local event) whether your request succeeds or fails, even if it is a synchronous request, you can trigger the event when the request completes
Global event global is triggered when the request completes
(global event) triggered when no Ajax is in progress
While local events are covered in previous functions, we'll focus on global events. If an object is being monitored for global events, the AJAX actions in the global world will affect it. For example, when the page is doing an AJAX operation, the DIV with the ID "loading" is displayed:


Global events can also help you write global error responses and success responses without having to set them individually for each AJAX request. It is important to note that parameters for global events are useful. In addition to ajaxStart and ajaxOptions, other events have three parameters: event, XMLHttpRequest and ajaxOptions. The first parameter is the event itself; The second is the XHR object; The third is the ajax parameter object that you pass. Displaying a global AJAX case in an object:

$("#msg").beforeSend(function(e,xhr,o) {
 $(this).html(" Is requesting "+o.url);
 }).ajaxSuccess(function(e,xhr,o) {
 $(this).html(o.url+" The request is successful ");
 }).ajaxError(function(e,xhr,o) {
 $(this).html(o.url+" The request failed ");

Obviously, the third parameter also helps you pass the custom parameter you added in the AJAX event. On a single AJAX request, you can set the value of global to false to make the request independent of the AJAX global event.

   url: "request.php",
   global: false,
   //Disable global Ajax events.

If you want to set parameters for global AJAX, you will use the ajaxSetup() function. For example, pass all AJAX requests to requested.php; Disable global methods; Mandatory POST method:

  url: "request.php",
  global: false,
  type: "POST"

Something you have to know
Writing AJAX definitely involves getting the values from the page. Here's a quick list:

Val ()
The val() function can return the value of a form component, such as any type of input. With the help of selectors, you can easily get the values of elements such as option groups, input fields, buttons, etc.

//Returns the value
of the textbox with the name info $("input[name='pass']:password").val();
//Returns the value
of the password box with the name pass $("input[name='save']:radio").val();
//Returns the value of the radio item named save
//And so on

Serialize ()

The serialize function converts all the values of the form object to a sequence of strings. This is handy if you want to write a GET request.
SerializeArray () is similar to serialize(), except that it returns a JSON object.

PS: this site also provides several powerful json parsing, conversion and formatting tools for you to choose from. I believe that the following json format data processing will be helpful for you:

Online JSON code verification, verification, beautification, formatting tools:
(link: http://tools.jb51.net/code/json)

Online XML/JSON inter-conversion:
(link: http://tools.jb51.net/code/xmljson)

Json code online formatting/beautification/compression/editing/conversion tools:
(link: http://tools.jb51.net/code/jsoncodeformat)

C language style /HTML/CSS/json code format beautification tool:
(link: http://tools.jb51.net/code/ccode_html_css_json)

Related articles: