Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Jquery Ajax request

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to implement the Jquery Ajax request, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

JQuery is indeed a good lightweight JS framework, which can help us develop JS applications quickly and change our habit of writing JavaScript code to some extent.

Let's cut the crap and get to the point. Let's first look at some simple methods that encapsulate jQuery.ajax () to facilitate our use. Of course, if you want to deal with complex logic, you still need to use jQuery.ajax () (we'll talk about this 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) callback function when the request is completed (it does not need to be success).

This method is passed in GET mode by default. If the [data] parameter is passed in, it will be automatically converted to POST mode. In jQuery 1.2, selectors can be specified to filter loaded HTML documents, and only filtered HTML code will be inserted into DOM. The syntax looks like "url # some > selector".

This method makes it easy to dynamically load some HTML files, such as forms.

Sample code:

$(".ajax.load") .load ("[url] http://www.cnblogs.com/QLeelulu/archive/2008/03/30/1130270.html[/url] .post", function (responseText, textStatus, XMLHttpRequest) {this;// here this points to the current DOM object, that is, $(".ajax.load") [0] / / alert (responseText); / / the content returned by the request / / alert (textStatus); / / request status: success,error / / alert (XMLHttpRequest) / / XMLHttpRequest object})

The results will be displayed here.

Note: do not know why URL write absolute path will make an error under FF, please tell me if you know. The following get () and post () examples use absolute paths, so you will make an error under FF and will not see the result returned. There are also get () and post () examples that are called across domains, and find that there is no way to get the results after they are uploaded, so the run button is removed.

2. JQuery.get (url, [data], [callback]): use GET to make 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, expressed 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 something goes wrong, use $.ajax.

Sample code:

The data returned by $.get (". / Ajax.aspx", {Action: "get", Name: "lulu"}, function (data, textStatus) {/ / can be xmlDoc, jsonObj, html, text, etc. This; / / here this points to the option configuration information requested by Ajax. Please refer to the following figure alert (data); / / alert (textStatus); / / request status: success,error, etc. Of course, error cannot be captured here, because the callback function / / alert (this) will not be run at all during error.})

Click to send the 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 to make asynchronous requests

Parameters:

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

Data (Map): (optional) data to be sent to the server in the form of key-value pairs 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 be the type of client request (JSON,XML, etc.)

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 something goes wrong, 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; / / for the option configuration information of this Ajax request, please refer to this alert (data.result) mentioned by jQuery.get ();}, "json")

Click submit:

The format of the request is set to "json":

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

Notice that alert (data.result); because the Accept header is set to "json", the data returned here is an object and does not need to be converted to an object with eval ().

4. JQuery.getScript (url, [callback]): request to load and execute a JavaScript file through GET.

Parameters.

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

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

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

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

Load and execute test.js.

JQuery Code:

The copy code is as follows:

$.getScript ("test.js")

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

JQuery Code:

$.getScript ("AjaxEvent.js", function () {alert ("AjaxEvent.js loading and execution is complete. Click the Get or Post button above to see the difference?") ;})

Click on the above Load request again after loading to see what's different.

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 on each Ajax request, for example:

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

The global event is triggered by each Ajax request, and it broadcasts to all elements in the DOM, and 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 on specific requests, as long as we set the global option:

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

The following is a complete list of Ajax events officially given by jQuery:

AjaxStart (Global Event)

This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.

BeforeSend (Local Event)

This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)

AjaxSend (Global Event)

This global event is also triggered before the request is run.

Success (Local Event)

This event is only called if the request was successful (no errors from the server, no errors with the data).

AjaxSuccess (Global Event)

This event is also only called if the request was successful.

Error (Local Event)

This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).

AjaxError (Global Event)

This global event behaves the same as the local error event.

Complete (Local Event)

This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

AjaxComplete (Global Event)

This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.

AjaxStop (Global Event)

This global event is triggered if there are no more Ajax requests being processed.

Please refer to the API documentation for specific global events.

All right, let's start with the most powerful Ajax request method $.ajax () in jQuery.

JQuery.ajax (options): load remote data through a HTTP request

This is the underlying AJAX implementation of jQuery. For easy-to-use high-level implementations, see $. Get, $. Post, etc.

$.ajax () returns the XMLHttpRequest object it created. In most cases you do not need to manipulate the object directly, but in special cases you can use it to terminate the request manually.

Note: if you specify the dataType option, make sure that the server returns the correct MIME information (for example, xml returns "text/xml"). The wrong MIME type can lead to unpredictable errors. See Specifying the Data Type for AJAX Requests.

When the datatype type is set to''script'', all remote (not in the same domain) POST requests are converted back to GET mode.

Ajax () has only one parameter: the parameter key/value object, which contains information about each configuration and callback function. See below for detailed parameter options.

In jQuery 1.2, you can load JSON data across domains, and you need to set the data type to JSONP when using it. When calling a function in the form of JSONP, such as "myurl?callback=?" Will jQuery be replaced automatically? Is the correct function name to execute the callback function. When the data type is set to "jsonp", jQuery automatically calls the callback function. (I don't quite understand this.)

Parameter list:

The parameter name type describes the address at which the urlString (default: current page address) sends the request. TypeString (default: "GET") request method ("POST" or "GET"), default is "GET". Note: other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support them. TimeoutNumber sets the request timeout in milliseconds. This setting overrides the global setting. AsyncBoolean (default: true) by default, all requests are asynchronous. If you need to send a synchronization request, set this option to false. Note that the synchronization request will lock the browser, and other user actions must wait for the request to complete. BeforeSendFunction can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. The XMLHttpRequest object is the only parameter.

Function (XMLHttpRequest) {this; / / the options for this ajax request} cacheBoolean (default: true) jQuery 1.2 new feature, set to false will not load request information from the browser cache. Callback function after the completion of the completeFunction request (called when the request succeeds or fails). Parameter: XMLHttpRequest object, success information string.

Function (XMLHttpRequest, textStatus) {this; / / the options for this ajax request} contentTypeString (default: "application/x-www-form-urlencoded") content encoding type when sending information to the server. The default value is suitable for most applications. DataObject

The data that String sends to the server. Will be automatically converted to the request string format. The GET request will be appended to the URL. Check the description of the processData option to disable this automatic conversion. Must be in Key/Value format. If it is an array, jQuery automatically corresponds to the same name for different values. For example, {foo: ["bar1", "bar2"]} is converted to''& foo=bar1&foo=bar2''. DataTypeString

The type of data expected to be returned by the server. If not specified, jQuery will automatically return responseXML or responseText based on the HTTP package MIME information and pass it as a callback function parameter. Available values:

"xml": returns the XML document, which can be processed with jQuery.

"html": returns plain text HTML information; contains script elements.

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

"json": returns JSON data.

"jsonp": JSONP format. When calling a function in the form of JSONP, such as "myurl?callback=?" Will jQuery be replaced automatically? Is the correct function name to execute the callback function.

ErrorFunction (default: automatic judgment (xml or html)) this method is called when the request fails. This method takes three parameters: the XMLHttpRequest object, the error message, and (possibly) the captured error object.

Function (XMLHttpRequest, textStatus, errorThrown) {/ / normally textStatus and errorThown have only one of the values this; / / the options for this ajax request} globalBoolean (default: true) whether the global AJAX event is triggered. Setting to false will not trigger global AJAX events, such as ajaxStart or ajaxStop. Can be used to control different Ajax event ifModifiedBoolean (default: false) to get new data only when the server data changes. Use HTTP package Last-Modified header information to determine. ProcessDataBoolean (default: true) by default, the data sent is converted to an object (not a string technically) to match the default content type "application/x-www-form-urlencoded". Set to false if you want to send DOM tree information or other information that you do not want to convert. Callback function after a successful successFunction request. This method takes two parameters: the server returns the data and the status

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

There are several Ajax event parameters: beforeSend, success, complete, error. We can define these events to handle our every Ajax request well. Notice that the this in these Ajax events points to the option information requested by the Ajax (refer to the picture of this when talking about the get () method).

Please read the above parameter list carefully, if you want to use jQuery for Ajax development, then you must be familiar with these parameters.

Sample code to get the title of the article on the home page of the blog park:

$.ajax ({type: "get", url: "[url] http://www.cnblogs.com/rss[/url]", beforeSend: function (XMLHttpRequest) {/ / ShowLoading ();}, success: function (data, textStatus) {$(" .ajax.ajaxResult "). Html ("); $(" item ", data) .each (function (I, domEle) {$(" .ajax.ajaxResult "). Append ("+ $(domEle) .children (" title "). Text () +") });}, complete: function (XMLHttpRequest, textStatus) {/ / HideLoading ();}, error: function () {/ / request error handling}})

Other

JQuery.ajaxSetup (options): sets the global AJAX default options.

Set the default address of the AJAX request to "/ xmlhttp/", disable triggering global AJAX events, and use POST instead of the default GET method. Subsequent AJAX requests no longer set any option parameters.

JQuery Code:

$.ajaxSetup ({url: "/ xmlhttp/", global: false, type: "POST"}); $.ajax ({data: myData})

Serialize () and serializeArray ()

Serialize (): the content of the ordinal table is a string.

SerializeArray (): serializes table elements (similar to the'. Serialize () 'method) to return JSON data structure data.

Example:

HTML Code:

Results: B > p > Singleoption > Single2option > select > Multipleoption > Multiple2option > Multiple3option > select > check1 check2 radio1 radio2form >

The result of serializeArray () is:

Here's why a general request can download a file, but an Ajax request cannot.

That is because of response reasons, the general request browser will handle the server output response, such as generating png, file download, etc., ajax request is only a "character" request, you can read the returned response, but only read it, it cannot be executed, to put it bluntly, js cannot call the browser's download processing mechanism and procedures.

After reading the above, have you mastered how to implement the Jquery Ajax request? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report