In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use the ajax function", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the ajax function.
The ajax function refers to the jQuery.ajax () function, which is used to load remote data through background HTTP requests, which is implemented by AJAX technology encapsulated by jQuery. Through this function, we can get the data on the remote server without refreshing the current page.
This article operating environment: Windows7 system, jquery3.2.1 version, Dell G3 computer.
What is the ajax function?
Detailed explanation of jQuery.ajax () function
The jQuery.ajax () function is used to load remote data through a background HTTP request.
The jQuery.ajax () function is an implementation of AJAX technology encapsulated by jQuery, through which we can get the data on the remote server without refreshing the current page.
The jQuery.ajax () function is the underlying AJAX implementation of jQuery. The functions jQuery.get (), jQuery.post (), load (), jQuery.getJSON (), jQuery.getScript (), and so on are all simplified forms of this function (all call this function, but the parameter settings are different or omitted).
This function belongs to a global jQuery object (which can also be understood as a static function).
Parameters.
Please find the corresponding parameter according to the parameter name defined in the previous syntax section.
Parameter describes the urlString type URL request string. The settings optional / Object type has an Object object, where each property is used to specify the additional parameter settings required to send the request.
The parameter settings is an object, and jQuery.ajax () recognizes the following properties of the object (they are all optional):
Accepts-Object type
Default value: depends on the dataType property.
The content type request header sent is used to tell the server what type of response the browser can receive from the server.
Async-Boolean type
Default value: true.
Indicates whether it is an asynchronous request. The synchronization request locks the browser and nothing else can be done until the remote data is obtained.
BeforeSend---Function Typ
Specifies the callback function that needs to be executed before the request is sent. The function also has two parameters: one is the jqXHR object, and the other is the current settings object. This is an Ajax event, and if the function returns false, the ajax request will be cancelled.
Cache---Boolean Typ
Default value: true (when dataType is' script' or 'jsonp', the default is false).
Indicates whether URL requests are cached. Setting it to false forces the browser not to cache the current URL request. This parameter is valid only for HEAD and GET requests (the POST request itself is not cached).
Complete---Function/Array Typ
Specifies the callback function that needs to be executed after the request completes, regardless of success or failure. The function also takes two parameters: a jqXHR object and a string representing the status of the request ('success',' notmodified', 'error',' timeout', 'abort', or' parsererror'). This is an Ajax event.
Starting with jQuery 1.5, the attribute value can be multiple functions in the form of an array, each of which will be executed in a callback.
Contents---Object Type 1.5 added
An object paired with "{string: regular expression}" to determine how jQuery will parse the response, given its content type.
ContentType---String Typ
Default value: 'application/x-www-form-urlencoded; charset=UTF-8'.
Sends data to the server using the specified content encoding type. The W3C XMLHttpRequest specification states that charset is always UTF-8, and if you change it to another character set, you can't force the browser to change the character encoding.
Context---Object Typ
The context object used to set the Ajax-related callback function (that is, the this pointer within the function).
Converters-Object Type 1.5 added
Default value: {'* text': window.String, 'text html': true,' text json': jQuery.parseJSON, 'text xml': jQuery.parseXML}.
A data type converter. The value of each converter is a function that returns the converted value of the response.
CrossDomain---Boolean Type 1.5 added
Default value: false for same domain request and true for cross-domain request.
Indicates whether it is a cross-domain request. If you want to force cross-domain requests (such as JSONP) in the same domain, set it to true. For example, this allows server-side redirection to another domain.
Any type of data
The data sent to the server is automatically converted to a string type. If it is a GET request, it will be appended to the URL.
DataFilter---Function Typ
Specifies the callback function that processes the raw data of the response. The function also has two arguments: a string that represents the raw data of the response, and a dataType property string.
DataType---String Typ
Default value: jQuery intelligent guess, guess range (xml, json, script or html)
Specifies the type of data to return. The value of this property can be:
'xml': returns the XML document, which can be processed using jQuery.
'html': returns a HTML string.
'script': returns the JavaScript code. The results are not automatically cached. Unless the cache parameter is set. Note: when making remote requests (not in the same domain), all POST requests will be converted to GET requests. (because the script tag of DOM will be used to load)
'json': returns JSON data. The JSON data will be parsed using strict syntax (attribute names must be in double quotes, and all strings must be in double quotes), and an error will be thrown if parsing fails. Starting with jQuery 1.9, the response to empty content will return null or {}.
'in jsonp': JSONP format. When you call a function in the form of JSONP, such as "url?callback=?", jQuery automatically replaces the second? Is the correct function name to execute the callback function.
'text': returns a plain text string.
Error---Function/Array Typ
Specifies the callback function to be executed when the request fails. The function takes three parameters: the jqXHR object, the request status string (null, 'timeout',' error', 'abort', and' parsererror'), and the error message string (the text description of the response status, such as' Not Found' or 'Internal Server Error'). This is an Ajax event. Cross-domain scripts and cross-domain JSONP requests do not call this function.
Starting with jQuery 1.5, the attribute value can be multiple functions in the form of an array, each of which will be executed in a callback.
Global---Boolean Typ
Default value: true.
Indicates whether a global Ajax event is triggered. Setting this value to false prevents global event handlers, such as ajaxStart () and ajaxStop (), from being triggered. It can be used to control various Ajax events.
Headers---Object Type 1.5 added
Default value: {}.
Specifies additional request header information in the form of an object. The request header X-Requested-With: XMLHttpRequest will always be added, but you can also change the default xmlhttRequest value here. The value in headers can override the request header set in the beforeSend callback function (that is, beforeSend is called first).
$.ajax ({url: "my.php", headers: {"Referer": "http://www.365mini.com" / / some browsers are not allowed to modify the request header," User-Agent ":" newLine "/ / some browsers are not allowed to modify the request header," X-Power ":" newLine "," Accept-Language ":" en-US "}}) IfModified---Boolean Typ
Default value: false.
Allows the current request to get new data only when the server data changes (if not changed, the browser gets the data from the cache). It uses HTTP header information Last-Modified to determine. Starting with jQuery 1.4, he also checks the 'etag' specified by the server to determine if the data has been modified.
IsLocal---Boolean type 1.5.1 New
Default value: depends on the current location protocol.
Allows you to treat the current environment as "local" (for example, a file system), even if jQuery does not recognize it this way by default. Currently, the following protocols will be considered local: file, *-extension and widget.
Jsonp---String Typ
Overrides the callback function name of the JSONP request. This value is used instead of "url?callback=?" The "callback" section in.
JsonpCallback---String/Function Typ
Specify a callback function name for the JSONP request. This value will be used to replace the random function name automatically generated by jQuery.
Starting with jQuery 1.5, you can also specify a function to return the desired function name.
MimeType---String type 1.5.1 New
A mime type is used to override the mime type of XHR.
Password---String Typ
The password used to respond to HTTP access authentication requests.
ProcessData---Boolean Typ
Default value: true.
By default, data passed in through the data attribute, if it is an object (technically, as long as it is not a string), is processed and converted into a query string 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.
ScriptCharset---String Typ
Sets the character set of the script file loaded by the request. Only when the dataType is "jsonp" or "script" and type is "GET" will it be used to force the modification of the charset. This is equivalent to setting the charset attribute of the tag. It is usually only used when the content encoding of the current page and remote data is not at the same time.
StatusCode---Object Type 1.5 added
Default value: {}.
An object consisting of a set of numeric HTTP codes and functions that are called when responding. For example:
$.ajax ({url: a_not_found_url, / / when responding to the corresponding status code, execute the corresponding callback function statusCode: {404: function () {alert ("Page not found");}, 200: function () {alert ("request successful");}) Success---Function/Array Typ
Specifies the callback function to be executed after the request is successful. This function takes three parameters: the data returned by the request, the response status string, and the jqXHR object.
Starting with jQuery 1.5, the attribute value can be multiple functions in the form of an array, each of which will be executed in a callback.
Timeout---Number Typ
Sets the millisecond value of the request timeout.
Traditional---Boolean Typ
If you want to serialize the parameters in the traditional way, set this property to true.
Type---String Typ
The default value is "GET".
Request type, which can be 'POST' or' GET'. Note: you can also use other request types such as' PUT', 'DELETE' here, but they are not supported by all browsers.
Url-String type
Default value: current page URL.
The target URL of the request.
Username-String type
The user name used to respond to HTTP access authentication requests.
Xhr-Function type
The default value is ActiveXObject (if available) under IE and XMLHttpRequest in other browsers.
A callback function that creates and returns a XMLHttpRequest object. You can override this property to provide your own XHR implementation, or to enhance its functionality.
XhrFieldsObject type 1.5.1 New
An object with multiple Field name-Field value pairs that is used to set local XHR objects. A pair of File name-File values sets the XHR object natively. For example, if necessary, you can use it to set the withCredentials property of the XHR object to true for cross-domain requests.
$.ajax ({url: a_cross_domain_url, / / set the withCredentials of the XHR object to true xhrFields: {withCredentials: true}}); Note:
1. If all your AJAX requests need to set some parameters in settings, you can use the jQuery.ajaxSetup () function to set global settings instead of setting them separately each time you execute jQuery.ajax ().
2. Before jQuery 1.4 (inclusive), the third parameter of the callback function for Ajax events such as complete, succes, error, etc., is not a jQuery-encapsulated jqXHR object, but a native XMLHttpRequest object.
Return value
The return value of the jQuery.ajax () function is of type jqXHR and returns the jqHXR object of the current request (jQuery 1.4 and previous versions returned native XMLHttpRequest objects).
Example & illustration
If no parameters are specified to jQuery.ajax (), the current page is requested by default, and the returned data is not processed.
In the settings object of the jQuery.ajax () function, the commonly used properties are: url, type, async, data, dataType, success, error, complete, beforeSend, timeout, and so on.
Please refer to the following initial HTML code:
The following is the jQuery sample code associated with the jQuery.ajax () function to demonstrate the specific use of the jQuery.ajax () function:
(there is only the first ajax () function on the demo page. Please copy the other code to the demo page and execute it separately.)
$.ajax ({url: "jquery_ajax.php", type: "POST", data: "name=codeplayer&age=18", success: function (data, textStatus, jqXHR) {/ / data is the returned data / / textStatus may be "success", "notmodified", etc / / jqXHR is the XMLHttpRequest object alert ("returned data" + data) encapsulated by jQuery;}}) $.ajax ({url: "jquery_ajax.php?page=1&id=3", type: "POST" / / jQuery will automatically convert the object data to "name=codeplayer&age=18&uid=1&uid=2&uid=3", data: {name: "codeplayer", age:18, uid: [1,2,3]} / / execute when the request is successful, success: function (data, textStatus, jqXHR) {alert ("returned data" + data) } / / execute when the request fails. Error: function (jqXHR, textStatus, errorMsg) {/ / jqXHR is a XMLHttpRequest object encapsulated by jQuery / / textStatus may be: null, "timeout", "error", "abort" or "parsererror" / / errorMsg may be: "Not Found", "Internal Server Error" and other alert ("request failed:" + errorMsg);}}) / / extract url separately as the first parameter (supported by jQuery 1.5 +) $.ajax ("jquery_ajax.php?action=type&id=3", {dataType: "json" / / returns data in JSON format, success: function (data, textStatus, jqXHR) {/ / assume that the returned string data is {"name": "CodePlayer" Age: 20} / / jQuery has helped us convert the JSON string to the corresponding JS object You can use alert (data.name) directly / / CodePlayer}}); $.ajax ({/ / notice that there is a parameter callback=? Url: "http://cross-domain/jquery_ajax.php?name=Jim&callback=?&age=21", async: false / / synchronous request. The browser will be locked after the request is sent, and the user cannot operate until the request is completed (regardless of success or failure). The js code will continue to execute. DataType: "jsonp" / / returns data in JSON format. Success: function (data, textStatus, jqXHR) {/ / assumes that the returned string data is {"site_name": "CodePlayer", "site_desc": "focus on programming development technology sharing"} / / jQuery has helped us convert the JSON string into the corresponding JS object. You can use alert (data.site_desc) directly / / focus on programming development technology sharing}}); $.ajax ({/ / load the specified js file into the current document url: "http://code.jquery.com/jquery-1.8.3.min.js", dataType:" script "}); at this point, I believe you have a deeper understanding of" how to use the ajax function ", you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.