Detailed discussion on the usage of jQuery Ajax of load post get and ajax

  • 2021-07-26 06:14:28
  • OfStack

Today, I saw some netizens in the group ask about the differences between Jquery Ajax (load, post, get, ajax). Now I have sorted out an article, hoping to help netizens. First, let's look at some simple methods.

These methods encapsulate jQuery. ajax () for our convenience, although jQuery. ajax () is still needed to deal with complex logic (this will be discussed later).

1. load (url, [data], [callback]): Load the remote HTML file code and insert it into DOM.

url (String): The URL address of the requested HTML page.

data (Map): (optional) key/value data sent to the server.

callback (Callback): (optional) The callback function when the request completes (need not be success's).

This method is passed by default in GET mode. If the [data] parameter has passed data, it will be automatically converted to POST mode. In jQuery 1.2, you can specify a selector,

To filter the loaded HTML document, DOM inserts only the filtered HTML code. The syntax is like "url # some > selector ".

This method can easily load some HTML files dynamically, such as forms.

Sample code:

$(". ajax. load"). load ("https://www. ofstack. com", function (responseText, textStatus, XMLHttpRequest) {this;//Here this points to the current DOM object,

Namely $(". ajax. load") [0]//alert (responseText); //Request returned content//alert (textStatus); //Request status: success, error//alert (XMLHttpRequest); //XMLHttpRequest object});

Note: I don't know why URL write absolute path in FF will be wrong, know the trouble to tell next. The following get () and post () examples use absolute paths, so under FF you will get an error and will not see the return result. There are also examples of get () and post (), both of which are called across domains. It is found that there is no way to get the results after being passed up, so the run button is removed.

2. jQuery. get (url, [data], [callback]): Use GET for asynchronous requests

Parameters:

url (String): The URL address from which the request was sent.

data (Map): (optional) The data to be sent to the server, represented as a key-value pair of Key/value, is appended to the request URL as QueryString.

callback (Function): (optional) callback function on successful loading (this method is called only if the return status of Response is success).

This is a simple GET request function to replace the complex $. ajax. The callback function can be called when the request is successful. If you need to execute the function when an error occurs, use $. ajax.

Sample code:

$. get ("./Ajax. aspx", {Action: "get", {Name: "lulu"}, function (data, textStatus) {//The returned data can be xmlDoc, jsonObj, html, text, etc. this;//Here this points to the option configuration information requested by Ajax, see the following figure alert (data);//alert (textStatus);//Request status:

Of course, error is not captured here, because the callback function//alert (this) will not be run at all when error;});

Click Send Request:

The this in the jQuery. get () callback function points to the option configuration information requested by Ajax:

3. jQuery. post (url, [data], [callback], [type]): Use POST for asynchronous requests

Parameters:

url (String): The URL address from which the request was sent.

data (Map): (Optional) The data to be sent to the server, represented as a key-value pair of Key/value.

callback (Function): (optional) callback function on successful loading (this method is called only if the return status of Response is success).

type (String): (Optional) The official description is: Type of data to be sent. It should actually be the type of client request (JSON, XML, and so on)

This is a simple POST request function to replace the complex $. ajax. The callback function can be called when the request is successful. If you need to execute the function when an error occurs, use $. ajax.

Sample code:

Ajax. aspx:

Response. ContentType = "application/json"; Response. Write ("{result: '" + Request ["Name"] + "Hello! (This message comes from the server)'}");

jQuery code:

$. post ("Ajax. aspx", {Action: "post", Name: "lulu"}, function (data, textStatus) {//data can be xmlDoc, jsonObj, html, text, etc.//this;//Refer to thisalert (data. result) as mentioned in jQuery. get () for option configuration information for this Ajax request;} , "json");

Click Submit:

The request is formatted as "json":

If you set the request format to "json", then you do not set Response to return ContentType: Response. ContentType = "application/json"; Then you will not be able to capture the returned data.

Note 1, alert (data. result); Since the Accept header is set to "json", the data returned here is an object, and there is no need to use eval () to convert it to an object.

4. jQuery. getScript (url, [callback]): Request to load and execute an JavaScript file through GET.

Parameter

url (String): The address of the JS file to be loaded.

callback (Function): (optional) callback function after successful loading.

Before jQuery version 1.2, getScript could only call the same domain JS file. In 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in global scope. If you add a script through getScript, add a delay function.

This method can be used, for example, to load the JS file required by the editor only when the editor focus (). Here's a look at some sample code:

Load and execute test. js.

jQuery code:

$.getScript("test.js");

Load and execute AjaxEvent. js, and display information after success.

jQuery code:

$. getScript ("AjaxEvent. js", function () {alert ("AjaxEvent. js is loaded and executed. You click the Get or Post button above again to see what's the difference?");} );

jQuery Ajax Event

Ajax requests generate several different events that we can subscribe to and process our logic in. There are two types of Ajax events in jQuery: local events and global events.

Local events are defined within the method at each Ajax request, for example:

$.ajax({beforeSend: function(){// Handle the beforeSend event},complete: function(){// Handle the complete event}// ...});

The global event is triggered with each Ajax request and is broadcast to all elements in the DOM. The script loaded in the getScript () example above is the global Ajax event. Global events can be defined as follows:

$("#loading").bind("ajaxSend", function(){$(this).show();}).bind("ajaxComplete", function(){$(this).hide();});

Or:

$("#loading").ajaxStart(function(){$(this).show();});

We can disable global events for specific requests by setting the global option:

$. ajax ({url: "test. html", global: false,//Disable global Ajax events.//...});


Related articles: