In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the Ajax usage of jQuery learning notes. The construction of Changsha website, combined with the form of examples, analyzes and summarizes the relevant skills of using ajax in jQuery, including ajax request, loading, processing, transmission, etc., friends who need can refer to it.
This paper gives an example to illustrate the Ajax usage of jQuery learning notes. Share with you for your reference, the details are as follows:
I. Ajax request
1. JQuery.ajax (options)
Load remote data through a HTTP request. 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. 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.
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.
Note: if dataType is set to "script", all POST requests will be converted to GET requests when remote requests are made (not in the same domain). (because the script tag of DOM will be used to load)
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.
Return value: XMLHttpRequest
Parameters:
Options (optional): AJAX request settings. All options are optional.
Option
(1), async (Boolean): (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.
(2), beforeSend (Function): a function that modifies the XMLHttpRequest object before sending the request, such as adding a custom HTTP header.
The XMLHttpRequest object is the only parameter. This is an Ajax event. If false is returned, you can cancel this ajax request.
Function (XMLHttpRequest) {this; / / the options parameter passed when this AJAX request is called}
(3), cache (Boolean): (default: false is the default when true,dataType is script). JQuery 1.2 new feature, set to false will not load request information from the browser cache.
(4), complete (Function): callback function after the request is completed (called when the request succeeds or fails).
Parameters: the XMLHttpRequest object and a string that describes the type of successful request. This is an Ajax event
Function (XMLHttpRequest, textStatus) {this; / / the options parameter passed when this AJAX request is called}
(5), contentType (String): (default: "application/x-www-form-urlencoded") the type of content encoding when sending information to the server. The default value is suitable for most applications.
(6), data (Object,String): data sent 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'.
(7), dataFilter (Function): a function that preprocesses the raw data returned by Ajax. Provide two parameters, data and type: data is the raw data returned by Ajax, and type is when jQuery.ajax is called
The dataType parameter provided. The value returned by the function will be further processed by jQuery.
Function (data, type) {/ / pre-process the raw data returned by Ajax return data / / return the processed data}
(8), dataType (String): (default: intelligent judgment xml or html)
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; the included script tag is executed when the dom is inserted. "script": returns plain text 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 DOM's script tag will be used to load) "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. "text": returns a plain text string
(9), error (Function): (default: automatic judgment (xml or html)) call time when the request fails. There are three parameters: XMLHttpRequest object, error message, and (optional) captured error object.
If an error occurs, the error message (the second parameter) may be "timeout", "error", "notmodified" and "parsererror" in addition to getting null. Ajax event.
Function (XMLHttpRequest, textStatus, errorThrown) {/ / usually only one of textStatus and errorThrown will contain information this; / / the options parameter passed when this AJAX request is called}
(10), global (Boolean): (default: true) whether the global AJAX event is triggered. Setting to false will not trigger global AJAX events, such as ajaxStart or ajaxStop, which can be used to control different Ajax events.
(11), ifModified (Boolean): (default: false) get new data only when the server data changes. Use HTTP package Last-Modified header information to determine.
(12), jsonp (String): overrides the name of the callback function in an jsonp request. This value is used instead of in "callback=?" The "callback" part of the URL parameter of this GET or POST request
For example, {jsonp:'onJsonPLoad'} will cause "onJsonPLoad=?" Pass it to the server.
(13), password (String): password used to respond to HTTP access authentication request
(14), processData (Boolean): (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.
(15), scriptCharset (String): only when the dataType is "jsonp" or "script" and the type is "GET" will it be used to force the modification of charset. Local and remote content encoding is usually not used at the same time.
(16), success (Function): callback function after a successful request. Parameters: data returned by the server and processed according to the dataType parameter; a string describing the status. Ajax event.
Function (data, textStatus) {/ / data may be xmlDoc, jsonObj, html, text, etc. This; / / the options parameter passed when this AJAX request is called}
(17), timeout (Number): sets the request timeout (milliseconds). This setting overrides the global setting.
(18), type (String): (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.
(19), url (String): (default: current page address) the address at which the request is sent.
(20), username (String): user name used to respond to HTTP access authentication request
(21), xhr (Function): a XMLHttpRequest object needs to be returned. The default is ActiveXObject under IE and XMLHttpRequest in other cases. Used to rewrite or provide an enhanced
XMLHttpRequest object. This parameter is not available before jQuery 1.3.
Ps: the above part is the parameter settings commonly used in url type dataType data success calls, which can be used to successfully implement ajax calls.
Exampl
1 / / jQTest.js 2 function jqAjaxTest () {3 var jqRequestUrl = "AjaxHandler.ashx"; 4 / 1, load and execute a JS file 5 $.ajax ({6 type: "GET", 7 url: "js/jqLoadJs.js", 8 dataType: "script" 9}) 10 / 2. Load the latest version of a HTML page 11 $.ajax ({12 url: "test.htm", 13 cache: false, / / say 14 success: function (html) {15 / / alert (html); 16 $("# spanGetHtml"). Css ("display", "block"); 17 $("# spanGetHtml"). Css ("color", "red"); 18 $("# spanGetHtml") .append (html); 19} 20}) 21 / / 3. Get and parse a xml file (get xml from the server) 22 $.ajax ({23 type: 'GET', 24 dataType:' xml', / / you don't have to write here But never write text or html 25 url: jqRequestUrl + "? action=jquerGetXmlRequest", 26 success: function (xml) {27 / / correctly parse the server's xml file 28 $(xml) .find ("profile") .each (function (I) {29 var name = $(this) .children ("userName"). Text () / / take object text 30 var location = $(this) .children ("location"). Text (); 31 alert ("Xml at SERVER is gotten by CLIENT:" + name + "is living in" + location); 32}); 33}, 34 error: function (xml) {35 alert ('An error happend while loading XML document'); 36} 37}) 38 / / 4. Send XML data to server (client sends xml to server) 39 var xmlDocument = "" + 40 "jeff wong" + 41 "beijing" + 42 "; 43 $.ajax ({44 url: jqRequestUrl +"? action=jqueryXmlRequest ", 45 processData: false, / / set processData option to false to prevent automatic conversion of data format. 46 / / type: "xml", 47 cache: false, 48 type: "xml", 49 data: xmlDocument, 50 success: function (html) {51 alert (html); / / pop-up prompt 52 $("# spanResult"). Css ("display", "block"); 53 $("# spanResult"). Css ("color", "red"); 54 $("# spanResult") .html (html) / assign 55}, 56 error to a span element of the current dom: function (oXmlHttpReq, textStatus, errorThrown) {57 alert ("jquery ajax xml request failed"); 58 $("# spanResult"). Css ("display", "block"); 59 $("# spanResult"). Css ("color", "red"); 60 $("# spanResult"). Html ("jquery ajax xml request failed"); / / prompt error 61} 62}) 63 / / 5. Load data synchronously. Lock the browser when sending the request. Use synchronization when you need to lock user interaction. 64 var html = $.ajax ({65 / / No type defaults to GET mode 66 url: jqRequestUrl + "? action=syncRequest", 67 async: false 68}) .responseText; 69 alert (html); 70 / / 6, explicit get test 71 $.ajax ({72 type: "GET", 73 url: jqRequestUrl + "? action=jquery&userName=" + $("# txtUserName"). Val (), 74 cache: false, 75 success: function (html) {76 / alert (html) / / pop-up prompt 77 $("# spanResult"). Css ("display", "block"); 78 $("# spanResult"). Css ("color", "red"); 79 $("# spanResult") .html (html); / / assign a span element to the current dom 80}, 81 error: function (oXmlHttpReq, textStatus, errorThrown) {82 alert ("jquery ajax request failed"); 83 $("# spanResult"). Css ("display", "block") 84 $("# spanResult"). Css ("color", "red"); 85 $("# spanResult"). Html ("jquery ajax request failed"); / / prompt error 86} 87}); 88 / / 7, explicit POST test 89 $.ajax ({90 type: "POST", 91 url: jqRequestUrl, 92 data: "action=jquerySaveData&userName=jeffwong&location=beijing", 93 success: function (html) {94 alert (html); 95} 96}); 97}
2. Load (url, [data], [callback])
Load the remote HTML file code and insert it into DOM.
GET mode is used by default-automatically converts to POST mode when additional parameters are passed. 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".
Return value jQuery
Parameters.
Url (String): the URL of the HTML page to be loaded.
Data (Map,String): (optional) key/value data sent to the server. It is also possible to accept a string in jQuery 1.3.
Callback (Callback): (optional) callback function when loading successfully.
Exampl
1 function jqAjaxTest () {2 $("# spanResult") .load ("test.htm"); 3 $("# spanResult") .css ("display", "block"); 4 $("# spanResult") .css ("color", "red"); 5}
3. JQuery.get (url, [data], [callback], [type])
Request to load information through a remote HTTP GET.
This is a simple GET request function to replace complex .ajax. The callback function can be called when the request is successful. If you need to execute a function when something goes wrong, use .ajax.
Return value XMLHttpRequest
Parameters.
Url (String): the URL address of the page to be loaded
Data (Map): (optional) Key/value parameters to be sent.
Callback (Function): (optional) callback function when loading successfully.
Type (String): (optional) returns the content format, xml, html, script, json, text, _ default.
Exampl
1 function jqAjaxTest () {2 var jqRequestUrl = "AjaxHandler.ashx"; 3 $.get (jqRequestUrl + "? action=jquery", {userName: "jeff wong", location: "beijing"}, jqGetNormalCallBack, 'text'); / / return data type 4} 5 function jqGetNormalCallBack (oData) {6 $("# spanResult") .html (oData) / / json data binding is directly done here. The next jquery method will handle 7 $("# spanResult") .css ("display", "block"); 8 $("# spanResult") .css ("color", "red"); 9}
Ps: in this case, we are returning a piece of data of type json, which is not processed on the client side and will be improved in the next method (jQuery.getJSON).
4. JQuery.getJSON (url, [data], [callback])
Load JSON data through an HTTP GET request.
In jQuery 1.2, you can load JSON data from other domains, such as "myurl?callback=?", by using a callback function in the form of JSONP. Will jQuery be replaced automatically? Is the correct function name to execute the callback function. Note: the code after this line will be executed before the callback function is executed.
Return value XMLHttpRequest
Parameters.
Url (String): send the request address. Data (Map): (optional) Key/value parameters to be sent. Callback (Function): (optional) callback function when loading successfully.
Exampl
1 function jqAjaxTest () {2 var jqRequestUrl = "AjaxHandler.ashx"; 3 / / getJSON method call 4 $.getJSON (jqRequestUrl + "? action=jquery", {userName: "jeff wong", location: "beijing"}, jqGetJsonCallBack); / / return json data type 5} 6 / / A pair of json data for processing (oData is json data) 7 function jqGetJsonCallBack (oData) {8 var oJsonStr = "" 9 / / take the data from json and present 10 oJsonStr + = "userName:" + oData.userName + "location:" + oData.location + ""; 11 / / display all data in div 12 $("# divResult") .html (oJsonStr); 13 $("# divResult"). Css ("display", "block"); 14 $("# divResult"). Css ("color", "red"); 15}
5. JQuery.getScript (url, [callback])
Load and execute a JavaScript file through a HTTP GET request.
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.
Return value XMLHttpRequest
Parameters.
Url (String): the address of the JS file to be loaded.
Callback (Function): (optional) callback function after successful loading.
Exampl
1 function jqAjaxTest () {2 var jsUrl = "js/jqLoadJs.js"; 3 / / getScript method call 4 $.getScript (jsUrl, jqGetJsCallBack); 5} 6 / / oData returns the contents of the js file under the entire js path 7 function jqGetJsCallBack (oData) {8 alert (oData); 9}
6. JQuery.post (url, [data], [callback], [type])
Request to load information through a remote HTTP POST.
This is a simple POST request function to replace complex .ajax. The callback function can be called when the request is successful. If you need to execute a function when something goes wrong, use .ajax.
Return value XMLHttpRequest
Parameters.
Url (String): send the request address.
Data (Map): (optional) Key/value parameters to be sent.
Callback (Function): (optional) callback function when it is sent successfully.
Type (String): (optional) returns the content format, xml, html, script, json, text, _ default.
Exampl
1 function jqAjaxTest () {2 var jqRequestUrl = "AjaxHandler.ashx"; 3 $.post (jqRequestUrl + "? action=jquery", {userName: "jeff wong", location: "beijing"}, jqPostCallBack, "text"); / / return text data type 4} 5 function jqPostCallBack (oData) {6 / / display all data in div 7 $("# divResult") .html (oData); 8 $("# divResult"). Css ("display", "block") 9 $("# divResult") .css ("color", "red"); 10}
II. Ajax event
1. AjaxComplete (callback)
Executes the function when the AJAX request is completed. Ajax event.
The XMLHttpRequest object and settings are passed as arguments to the callback function.
Return value jQuery
Parameters.
Callback (Function): function to be executed
Exampl
1 function jqAjaxTest () {2 var jqRequestUrl = "AjaxHandler.ashx"; 3 $.post (jqRequestUrl + "? action=jquery", {userName: "jeff wong", location: "beijing"}, jqPostCallBack, "text"); / / return text data type 4 / / function 5 $("# divResult") .ajaxComplete (function (event, request, settings) {6 $(this) .append ("request completed."); 7}) 8} 9 function jqPostCallBack (oData) {10 / / display all data in div 11 $("# divResult") .html (oData); 12 $("# divResult") .css ("display", "block"); 13 $("# divResult") .css ("color", "red"); 14}
2. AjaxError (callback)
Executes the function when an error occurs in the AJAX request. Ajax event.
The XMLHttpRequest object and settings are passed as arguments to the callback function. The caught error can be passed as the last parameter.
Return value jQuery
Parameters.
Callback (Function): function to be executed
1 function (event, XMLHttpRequest, ajaxOptions, thrownError) {2 / / thrownError is passed 3 this; / / listening dom element 4} only when an exception occurs
Exampl
1 function jqAjaxTest () {2 var jqRequestUrl = "AjaxHandlers.ashx"; / / correct file name AjaxHandler.ashx intentionally misspelled here and triggered the ajaxError event 3 $.post (jqRequestUrl + "? action=jquery", {userName: "jeff wong", location: "beijing"}, jqPostCallBack, "text") 4} 5 / / execute the function when an error occurs in the AJAX request (this paragraph can also be placed in the jqAjaxTest function) 6 $("# divResult") .ajaxError (function (event, request, settings) {7 $("# divResult"). Css ("display", "block"); 8 $("# divResult"). Css ("color", "red"); 9 $(this) .append ("error page:" + settings.url); 10}) 11 function jqPostCallBack (oData) {12 / / display all data in div 13 $("# divResult") .html (oData); 14 $("# divResult") .css ("display", "block"); 15 $("# divResult") .css ("color", "red"); 16}
3. AjaxSend (callback)
Execute the function before the AJAX request is sent. Ajax event.
The XMLHttpRequest object and settings are passed as arguments to the callback function.
Return value jQuery
Parameters.
Callback (Function): function to be executed
Exampl
1 function jqAjaxTest () {2 var jqRequestUrl = "AjaxHandler.ashx"; 3 $.post (jqRequestUrl + "? action=jquery", {userName: "jeff wong", location: "beijing"}, jqPostCallBack, "text"); 4} 5 / / execute function 6 $("# divResult") .ajaxSend (function (evt, request, settings) {7 $("# divResult"). Css ("display", "block") before the AJAX request is sent 8 $("# divResult"). Css ("color", "red"); 9 $(this) .append ("start request:" + settings.url + "); 10}); 11 function jqPostCallBack (oData) {12 / / display all data in div 13 $(" # divResult ") .append (oData); 14 $(" # divResult ") .css (" display "," block "); 15 $(" # divResult "). Css (" color "," red "); 16}
4. AjaxStart (callback)
The function is executed at the beginning of the AJAX request. Ajax event.
Return value jQuery
Parameters.
Callback (Function): function to be executed
Exampl
1 function jqAjaxTest () {2 var jqRequestUrl = "AjaxHandler.ashx"; 3 $.post (jqRequestUrl + "? action=jquery", {userName: "jeff wong", location: "beijing"}, jqPostCallBack, "text"); 4} 5 / / AJAX request starts with function 6 $("# divResult") .ajaxStart (function () {7 $("# divResult"). Css ("display", "block") 8 $("# divResult"). Css ("color", "red"); 9 $(this) .append ("request started"; 10}); 11 function jqPostCallBack (oData) {12 / / display all data in div 13 $("# divResult") .append (oData); 14 $("# divResult") .css ("display", "block"); 15 $("# divResult"). Css ("color", "red"); 16}
5. AjaxStop (callback)
Executes the function when the AJAX request ends. Ajax event.
Return value jQuery
Parameters.
Callback (Function): function to be executed
Exampl
1 function jqAjaxTest () {2 var jqRequestUrl = "AjaxHandler.ashx"; 3 $.post (jqRequestUrl + "? action=jquery", {userName: "jeff wong", location: "beijing"}, jqPostCallBack, "text"); 4} 5 / / execute function 6 $("# divResult") .ajaxStop (function () {7 $(this) .append ("request ended") at the beginning of the AJAX request; 8}) 9 function jqPostCallBack (oData) {10 / / display all data in div 11 $("# divResult") .append (oData); 12 $("# divResult") .css ("display", "block"); 13 $("# divResult") .css ("color", "red"); 14}
6. AjaxSuccess (callback)
Executes the function when the AJAX request is successful. Ajax event.
The XMLHttpRequest object and settings are passed as arguments to the callback function.
Return value jQuery
Parameters.
Callback (Function): function to be executed
Exampl
1 function jqAjaxTest () {2 var jqRequestUrl = "AjaxHandler.ashx"; 3 $.post (jqRequestUrl + "? action=jquery", {userName: "jeff wong", location: "beijing"}, jqPostCallBack, "text"); 4} 5 / / execute function 6 $("# divResult") .ajaxSuccess (function (evt, request, settings) {7 $(this) .append ("request successful"); 8 $(this) .append (settings.url) when the AJAX request succeeds 9}); 10 function jqPostCallBack (oData) {11 / / display all data in div 12 $("# divResult") .append (oData); 13 $("# divResult") .css ("display", "block"); 14 $("# divResult") .css ("color", "red"); 15}
III. Other
1. JQuery.ajaxSetup (options)
Sets the global AJAX default options.
For parameters, see the description of'$.ajax'.
Return value jQuery
Parameters.
Options (optional): option setting. All settings are optional.
Exampl
1 / / set the default address of AJAX request to "AjaxHandler.ashx", prohibit triggering global AJAX events, and use POST instead of the default GET method. Subsequent AJAX requests no longer set any option parameters. 2 $.ajaxSetup ({3 url: "AjaxHandler.ashx", 4 global: false, 5 type: "POST" 6})
2. Serialize ()
Serializes the contents of the form to a string.
Return value jQuery
Parameters.
Serializes the content of the form into a string for Ajax requests.
Exampl
1 $(document) .ready (function () {2 var oSerializedStr = $("form") .serialize (); / / serialize the form content to the string 3 $("# results") .append ("" + oSerializedStr + "); 4})
Document fragment
12 3 Results: 4 5 6 7 Single 8 Single2 9 10 11 Multiple 12 Multiple2 13 Multiple3 14 15 16 check1 17 18 check2 19 20 radio1 21 22 radio2 23 24 25
3. SerializeArray ()
Serializes the form content and returns JSON data structure data.
Return value jQuery
Parameters.
Serialize the form content as JSON for Ajax requests.
Exampl
1 $(document) .ready (function () {2 var fields = $("select,: radio") .serializeArray (); / / serialize forms select and raido to json 3 jQuery.each (fields, function (I, field) {4 $("# results") .append (field.value + "); 5}); 6}))
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
[oracle@rac01 ~] $crsctlUsage: crsctl check crs-checks the viability of the CRS stack
© 2024 shulou.com SLNews company. All rights reserved.