In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to use jQuery to achieve Ajax function conveniently and quickly, I believe many inexperienced people are at a loss about this. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Ajax enriches user pages and enhances the user experience. Using Ajax is a required course for all Web developers. Although the Ajax technology is not complex, the implementation will vary from developer to developer. JQuery provides a series of Ajax functions to help us unify this difference and make it easier to call Ajax.
51CTO recommended topic: jQuery from entry to proficiency in jQuery Power plug-in Parade
one。 Original Ajax and Ajax in jQuery
First of all, through an example, let's take a look at how easy it is for jQuery to implement Ajax. The following is an example of using the original Ajax:
In the above example, the data/AjaxGetCityInfo.aspx?resultType=html address returns a piece of HTML code.
Using the original Ajax, we need to do many things, such as creating XmlHttpRequest objects, judging the status of requests, writing callback functions, and so on.
JQuery Ajax $(function () {var xhr = new AjaxXmlHttpRequest (); $("# btnAjaxOld") .click (function (event) {var xhr = new AjaxXmlHttpRequest ()) Xhr.onreadystatechange = function () {if (xhr.readyState = = 4) {document.getElementById ("divResult") [xss_clean] = xhr.responseText }} xhr.open ("GET", "data/AjaxGetCityInfo.aspx?resultType=html", true); xhr.send (null);});}) / / Cross-browser acquisition of XmlHttpRequest object function AjaxXmlHttpRequest () {var xmlHttp Try {/ / Firefox, Opera 8.0, Safari xmlHttp = new XMLHttpRequest ();} catch (e) {/ / Internet Explorer try {xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP") } catch (e) {try {xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP") } catch (e) {alert ("your browser does not support AJAX!") ; return false;} return xmlHttp;} original Ajax call
With jQuery's Load method, all it takes is one sentence:
("# divResult") .load ("data/AjaxGetCityInfo.aspx", {"resultType": "html"})
I used to be an absolute proponent of the original Ajax and even abandoned Microsoft's Asp.net Ajax because I wanted code flexibility. Using the original Ajax makes it easier for me to finish my job, even if I write more code. But when I looked through other people's Ajax code and tried to modify it, I changed my mind-our code was dotted with functions to create XmlHttpRequest methods, or some Ajax programs were so illogical and structural that they were difficult to understand.
We can put the general method in a js file and tell everyone, "Hey guys, let's all use the method in this js." But at some point, some new outsourcers are unaware of the existence of this js file. And in fact, this general-purpose js is a public script library, I believe no one will think that developing a class library will be better than jQuery!
So I gave up my plan to make wheels, and everyone used jQuery to write Ajax-related methods to solve all kinds of differences and make the work more efficient.
Now that I'm just using jQuery's Ajax function, my page becomes concise:
two。 JQuery Ajax detailed explanation
JQuery provides several functions for sending Ajax requests. The core and most complex one is jQuery.ajax (options), which is a simplified call to all other Ajax functions. We can use this result when we want to have complete control over Ajax, otherwise it is more convenient to use simplified methods such as get, post, load, etc. So the jQuery.ajax (options) method is put into an introduction. Let's start with the simplest load method:
1. Load (url, [data], [callback])
Returns: jQuery Packaging set
Description:
The load method can load remote HTML file code and insert it into DOM.
GET mode is used by default, and Post mode is used if the data parameter is passed.
-automatically converts to POST mode when passing additional parameters. 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", and the default selector is "body > *".
Explanation:
Load is the simplest Ajax function, but there are limitations to its use:
1. It is mainly used for the Ajax interface that returns HTML directly.
2. Load is a jQuery wrapper method, which needs to be called on the jQuery wrapper set, and the returned HTML will be loaded into the object, even if the callback function is set.
However, there is no denying that the load interface is cleverly designed and easy to use. The following example demonstrates the use of the Load interface:
JQuery Ajax-Load $(function () {$("# btnAjaxGet") .click (function (event) {/ / send Get request $("# divResult") .load (".. / data/AjaxGetMethod.aspx?param=btnAjaxGet_click" + "& timestamp=" + (new Date ()) .getTime ());}) ("# btnAjaxPost") .click (function (event) {/ / send Post request $("# divResult") .load (".. / data/AjaxGetMethod.aspx", {"param": "btnAjaxPost_click"});}) ("# btnAjaxCallBack") .Click (function (event) {/ / send Post request, and execute callback function when it is returned. ("# divResult"). Load (".. / data/AjaxGetMethod.aspx", {"param": "btnAjaxCallBack_click"}, function (responseText, textStatus, XMLHttpRequest) {responseText = "Add in the CallBack Function!" + responseText $("# divResult") .html (responseText); / / or: $(this) .html (responseText);}) }) ("# btnAjaxFiltHtml") .click (function (event) {/ / send a Get request to filter out the item "Anshan" $("# divResult"). Load (".. / data/AjaxGetCityInfo.aspx?resultType=html" + "& timestamp=" + (new Date ()). GetTime () + "ul > li:not (: contains ('Anshan')")) });}) using Load to execute Get requests using Load to execute Post requests using the Load method with callback functions to filter the returned HTML content using selector
The above example shows how to use the Load method.
Tip: we should always pay attention to the browser cache, when using GET mode to add a timestamp parameter (net Date ()). GetTime () to ensure that the URL sent each time is different, can avoid browser cache.
Tip: when a space is added after the url parameter, such as "", an "unrecognized symbol" error occurs and the request can still be sent normally. However, HTML cannot be loaded into DOM. The problem is solved after deletion.
2.jQuery.get (url, [data], [callback], [type])
Returns: XMLHttpRequest
Description:
Request to load information through a remote HTTP GET.
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.
Explanation:
This function sends a Get request, and the parameters can be spliced directly in the url, such as:
$.get (".. / data/AjaxGetMethod.aspx?param=btnAjaxGet_click"); / / or pass it through the data parameter: $.get (".. / data/AjaxGetMethod.aspx", {"param": "btnAjaxGet2_click"})
The effect of the two methods is the same, and the data parameter is automatically added to the requested url.
If a parameter in url is passed through the data parameter, parameters with the same name are not automatically merged.
The signature of the callback function is as follows:
Function (data, textStatus) {/ / data could be xmlDoc, jsonObj, html, text, etc... This; / / the options for this ajax request}
Where data is the returned data, and testStatus represents the status code, which may be as follows:
"timeout", "error", "notmodified", "success", "parsererror"
The this in the callback function is to get a reference to the options object. For various instructions on options, see:
Http://docs.jquery.com/Ajax/jQuery.ajax#options
The type parameter refers to the type of data data, which may be the following values:
"xml", "html", "script", "json", "jsonp", "text".
The default is "html".
The jQuery.getJSON (url, [data], [callback]) method is equivalent to jQuery.get (url, [data], [callback], "json")
3. JQuery.getJSON (url, [data], [callback])
Returns: XMLHttpRequest
Equivalent to: jQuery.get (url, [data], [callback], "json")
Description:
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.
Explanation:
The getJSON function simply sets the type parameter of the get function to "JSON". The data obtained in the callback function is already parsed in JSON format:
$.getJSON (".. / data/AjaxGetCityInfo.aspx", {"resultType": "json"}, function (data, textStatus) {alert (data.length); alert (data [0] .CityName);})
The string returned by the server is as follows:
[{"pkid": "0997", "ProvinceId": "XJ", "CityName": "Aksu", "CityNameEn": "Akesu", "PostCode": "843000", "isHotCity": false}
{"pkid": "0412", "ProvinceId": "LN", "CityName": "Anshan", "CityNameEn": "Anshan", "PostCode": "114000", "isHotCity": false}]
In the example, the hungry I returned is an array. You can get the number of elements in the array using data.length, data [0] accesses * elements, and data [0] .CityName accesses the CityName attributes of * elements.
4.jQuery.getScript (url, [callback])
Returns: XMLHttpRequest
Equivalent to: jQuery.get (url, null, [callback], "script")
Description:
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.
Explanation:
In the past, when I used the dojo class library, the official default file did not support cross-domain * *, which led me to give up using dojo (although I found a cross-domain version on the Internet, it didn't feel enough * *). So I especially studied the core implementation and use of this function.
First of all, learn about the internal implementation of this function in jQuery, and still use the get function. All Ajax functions in jQuery, including get***, use jQuery.ajax (). GetScript passes in the type parameter with the value of "script". * the request with type as script is handled as follows in the Ajax function:
Var head = document.getElementsByTagName ("head") [0]; var script = document.createElement ("script"); script.src = s.url; / / the above code dynamically creates a block of script statements and adds it to head: head.appendChild (script); / / when the script is loaded, delete it from head: / / Handle Script loading if (! jsonp) {var done = false / / Attach handlers for all browsers script.onload = script.onreadystatechange = function () {if (! done & & (! this.readyState | | this.readyState = = "loaded" | | this.readyState = = "complete")) {done = true; success (); complete () / / Handle memory leak in IE script.onload = script.onreadystatechange = null; head.removeChild (script);};}
I mainly tested this function for cross-domain access and multi-browser support. Here are the results:
IE6FireFox Note non-cross-domain reference js through the callback function of data and textStatus are available cross-domain reference js through the callback function of data and textStatus are both undifined
Here are my key test statements, also used to demonstrate how to use the getScript function:
("# btnAjaxGetScript") .click (function (event) {$.getScript (".. / scripts/getScript.js", function (data, textStatus) {alert (data); alert (textStatus); alert (this.url);});}) ("# btnAjaxGetScriptCross") .click (function (event) {$.getScript ("http://resource.elong.com/getScript.js", function (data, textStatus) {alert (data); alert (textStatus); alert (this.url);});})
5. JQuery.post (url, [data], [callback], [type])
Returns: XMLHttpRequest
Description:
Request to load information through a remote HTTP POST.
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.
Explanation:
The specific usage is the same as get, except that the submission method is changed from "GET" to "POST".
6. JQuery.ajax (options)
Returns: XMLHttpRequest
Description:
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. See Specifying the Data Type for AJAX Requests.
Note: if dataType is set to "script", all remote (not under the same domain name) POST requests will be converted to GET requests. (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.
Explanation:
This is the core function of Ajax in jQuery. This function is called inside all the above functions that send Ajax requests. Options parameters support many parameters, which can be used to completely control ajax requests. The this object in the Ajax callback function is also an options object.
Because the most commonly used functions are the simplified get and post functions, I will not explain the options parameters in detail here. For options parameter documentation, please see: http://docs.jquery.com/Ajax/jQuery.ajax#options
three。 Ajax correlation function.
JQuery provides some related functions that can assist Ajax functions.
1. JQuery.ajaxSetup (options)
No return value
Description:
Sets the global AJAX default options options.
Explanation:
Sometimes we want to set the default behavior of all Ajax properties on the page. Then you can use this function to set the options option, and then the default options for all Ajax requests will be changed.
Options is an object. For properties that can be set, please connect here: http://docs.jquery.com/Ajax/jQuery.ajax#toptions
For example, when the page loads, I use the following code to set the default option option for Ajax:
$.ajaxsetup ({url: ".. / data/AjaxGetMethod.aspx", data: {"param": "ziqiu.zhang"}, global: false, type: "POST", success: function (data, textStatus) {$("# divResult") .html (data);}})
The above code sets the basic data needed for an Ajax request: request url, parameters, request type, and callback function after success.
We can then send the ajax request using the no-parameter get (), post () or ajax () methods. The complete sample code is as follows:
JQuery Ajax-Load $(document) .ready (function () {$.ajaxSetup ({url: ".. / data/AjaxGetMethod.aspx", data: {"param": "ziqiu.zhang"}, global: false, type: "POST" Success: function (data, textStatus) {$("# divResult") .html (data) }}); $("# btnAjax") .click (function (event) {$.ajax ();}); $("# btnGet") .click (function (event) {$.get ();}); $("# btnPost") .click (function (event) {$.post ();}) $("# btnGet2") .click (function (event) {$.get (".. / data/AjaxGetMethod.aspx", {"param": "other"}) Do not pass parameters call ajax () method do not pass parameters call get () method do not pass parameters call post () method pass parameters call get () method, use the global default callback function
Note that when using the get () or post () method, except that the type parameter will be rewritten to "GET" or "POST", the default global option is used as long as it is not passed. If an option is passed, such as a button that passes url and parameters, the call will take the passed option as final. Options that are not passed, such as callback functions, will still use global option settings.
2.serialize ()
Returns: String
Description:
The content of the ordinal table is a string and is used for Ajax requests.
Serialization is most commonly used when sending form data to the server. The serialized data is in a standard format and can be supported by almost all servers.
To work as well as possible, all serialized form fields are required to have a name attribute, and only one eid does not work.
Write the name property like this:
Explanation:
The serialize () function splices the form objects in the form to be sent to the server into a string. It is convenient for us to get form data when sending using Ajax. This is similar to a From that automatically submits the name / value of the form object to the url when it is submitted in Get.
For example, a form like this:
The generated string is: single=Single m=Multiple m=Multiple3&check=check2&radio=radio1
Hint: see chapter6\ 7-serialize.htm for the code.
3.serializeArray () Returns: Array
Returns: Array
Description:
Serializing table elements, similar to the '.serialize ()' method, returns JSON data structure data.
Note that this method returns a JSON object instead of a JSON string. You need to use plug-ins or third-party libraries for serialization.
Explanation:
I was disappointed to see the documentation. I used this function to get the JSON object, but there is no method in jQuery to convert the JSON object into a JSON string.
No suitable JSON compiler was found on the JSON official website, and jquery.json was chosen as the jQuery plug-in:
Http://code.google.com/p/jquery-json/
It is extremely easy to use:
Var thing = {plugin: 'jquery-json', version: 1.3}; var encoded = $.toJSON (thing); / /' {"plugin": "jquery-json", "version": 1.3} 'var name = $.evalJSON (encoded) .plugin; / / "jquery-json" var version = $.evalJSON (encoded) .version; / / 1.3
Using serializeArray () combined with the $. ToJSON method, we can easily get the JSON of the form object and convert it to a JSON string:
$("# results") .html ($.toJSON ($("form") .serializeArray ()
The result is:
[{"name": "single", "value": "Single"}, {"name": "param", "value": "Multiple"}, {"name": "param", "value": "Multiple3"}, {"name": "check", "value": "check2"}, {"name": "radio", "value": "radio1"}]
four。 Global Ajax event
In the options parameter property in jQuery.ajaxSetup (options), there is a global property:
Global
Type: Boolean
Default value: true
Description: whether to trigger a global Ajax event.
This property is used to set whether a global Ajax event is triggered. A global Ajax event is a series of events that accompany an Ajax request. There are mainly the following events:
The name indicates that ajaxComplete (callback) AJAX request completes execution function ajaxError (callback) AJAX request executes function ajaxSend (callback) AJAX request executes function ajaxStart (callback) AJAX request starts execution function ajaxStop (callback) AJAX request executes function ajaxSuccess (callback) AJAX request executes function when the request succeeds
Use an example to explain the trigger sequence of each event:
JQuery Ajax-AjaxEvent $(document) .ready (function () {$("# btnAjax") .bind ("click", function (event) {$.get (".. / data/AjaxGetMethod.aspx") }) $("# divResult") .ajaxComplete (function (evt, request, settings) {$(this) .append ('ajaxComplete');}) $("# divResult") .ajaxError (function (evt, request, settings) {$(this) .append (' ajaxError');}) $("# divResult") .ajaxSend (function (evt, request, settings) {$(this) .append ('ajaxSend')) }) $("# divResult") .ajaxStart (function () {$(this) .append ('ajaxStart');}) $("# divResult") .ajaxStop (function () {$(this) .append (' ajaxStop');}) $("# divResult") .ajaxSuccess (function (evt, request, settings) {$(this) .append ('ajaxSuccess');})})) Send Ajax request
The result is shown in the figure:
We can unfire the global Ajax event by setting the global property of the default options to false.
five。 Matters needing attention
If there are two parameters with the same name in the url sent by the Get request, such as two param parameters:
Http://localhost/AjaxGetMethod.aspx?param=Multiple¶m=Multiple3
Use the server-side method to get the param parameter:
If (! String.IsNullOrEmpty (HttpContext.Current.Request ["Param"])) {param = HttpContext.Current.Request ["Param"];}
The param obtained at this time is a string that separates multiple values with ",":
Multiple,Multiple3
six。 Summary
This paper introduces how to use jquery to implement Ajax function. The related functions used to send Ajax requests, such as load, get, getJSON and post, do not introduce too much about the core ajax method, mainly through the configuration of complex parameters to achieve complete control of Ajax requests. In addition, it explains the auxiliary functions of ajax, such as the serialize () method for serializing form objects into strings, and the serializeArray () method for serializing form objects into JSON objects. These are useful in using scripts to get data to interact with the server, and JSON format data frees us from messy property strings when dealing with large object programming.
JQuery also provides a special event to enter global ajax events, and these events can be set on an object and called during each life cycle of sending Ajax requests. Global events can be turned on or off by modifying the global property of the default options object.
After reading the above, have you mastered how to use jQuery to realize Ajax function conveniently and quickly? 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.
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
Replace some dates of the month with words
© 2024 shulou.com SLNews company. All rights reserved.