I. Summary
This series of articles will take you into the wonderful world of jquery, with many authors ' specific experiences and solutions, even if you can use jquery to find some cheats in your reading.
This article explains how to use jquery to quickly and easily implement AJAX functionality. Unify the way that all developers use Ajax.
Two. Foreword
Ajax makes the user page richer and enhances the user experience. Using AJAX is a required course for all web development. Although Ajax technology is not complex, the implementation is still different for each developer. jquery provides a series of Ajax functions to help us unify the differences and make it easier to invoke Ajax.
Three. Ajax in raw Ajax and jquery
First, take a look at how simple jquery is to implement Ajax. Here is an example of using raw AJAX:
<! DOCTYPE html PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> jQuery Ajax </ title>
<script type = "text / javascript">
$ (function ()
{
var xhr = new AjaxXmlHttpRequest ();
$ ("# btnAjaxOld"). click (function (event)
{
var xhr = new AjaxXmlHttpRequest ();
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
document.getElementById ("divResult"). innerHTML = xhr.responseText;
}
}
xhr.open ("GET", "data / AjaxGetCityInfo.aspx? resultType = html", true);
xhr.send (null);
});
})
// Get XmlHttpRequest object across browsers
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;
}
</ script>
</ head>
<body>
<button id = "btnAjaxOld"> raw Ajax call </ button> <br />
<br />
<div id = "divResult"> </ div>
</ body>
</ html>
In the example above, the Data/ajaxgetcityinfo.aspx?resulttype=html address returns a section of HTML code.
With raw Ajax, we need to do more things, such as creating XMLHttpRequest objects, judging request status, writing callback functions, and so on.
And using jquery's Load method, you need only one sentence:
$ ("#divResult"). Load ("HTML"});
Once I was an absolute supporter of original Ajax, and even abandoned Microsoft's ASP.net ajax because I wanted the highest level of code flexibility. Using raw Ajax makes me feel easier to do my job, even if I write more code. But when I looked at other people's Ajax code and tried to change it, I changed my view-our code was littered with functions that created XMLHttpRequest methods, or some AJAX programs were poorly logical and structurally difficult to read.
We can put the common method into a JS file, and then tell everyone "Hey buddies, all to use this JS method." But at some point some of the new outsourcing staff didn't know there was a JS file. And in fact, this generic JS is a common script class library, I believe no one will feel that the development of a class library will be better than jquery!
So I gave up the idea of making wheels, and everyone used jquery to write Ajax-related methods to solve all kinds of difference problems and make work more efficient.
Now just using jquery's Ajax functions, my pages have become concise:
<! DOCTYPE html PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> jQuery Ajax </ title>
<script type = "text / javascript" src = "scripts / jquery-1.3.2-vsdoc2.js"> </ script>
<script type = "text / javascript">
$ (function ()
{
$ ("# btnAjaxJquery"). click (function (event)
{
$ ("# divResult"). load ("data / AjaxGetCityInfo.aspx", {"resultType": "html"});
});
})
</ script>
</ head>
<body>
<button id = "btnAjaxJquery"> Load method using jQuery </ button>
<br />
<div id = "divResult"> </ div>
</ body>
</ html>
Four. JQuery Ajax detailed
jquery provides several functions for sending AJAX requests. One of the most central and complex of these is jquery.ajax (options), and all other Ajax functions are a simplified invocation of it. This result can be used when we want to fully control Ajax, otherwise it is easier to use simplified methods such as GET, post, load, and so on. So the Jquery.ajax (options) method is put to the last introduction. Let's first introduce the simplest load method:
1. load (URL, [data], [callback])
Returns: jquery Packaging set
Description
The Load method can load the remote HTML file code and insert it into the DOM.
Use the Get method by default, and the Post method if the data parameter is passed.
-Automatically converts to POST mode when additional parameters are passed. In JQuery 1.2, you can specify a selector to filter the loaded HTML document, and only the filtered HTML code will be inserted into the DOM. Syntax like "url #some > selector", the default selector is "body>*".
Explanation:
Load is the simplest Ajax function, but the use has limitations:
- It is primarily used for AJAX interfaces that return HTML directly
- Load is a jquery wrapper set method that needs to be invoked on the jquery wrapper set, and the returned HTML is loaded into the object, even if the callback function is set.
However, it is undeniable that the load interface is cleverly designed and easy to use. The following example demonstrates the use of the load interface:
<! DOCTYPE html PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> jQuery Ajax-Load </ title>
<script type = "text / javascript" src = "../ scripts / jquery-1.3.2-vsdoc2.js"> </ script>
<script type = "text / javascript">
$ (function ()
{
$ ("# btnAjaxGet"). click (function (event)
{
// Send a Get request
$ ("# divResult"). load ("../ data / AjaxGetMethod.aspx? param = btnAjaxGet_click" + "× tamp =" + (new Date ()). getTime ());
});
$ ("# btnAjaxPost"). click (function (event)
{
// Send a Post request
$ ("# divResult"). load ("../ data / AjaxGetMethod.aspx", {"param": "btnAjaxPost_click"});
});
$ ("# btnAjaxCallBack"). click (function (event)
{
// Send a Post request, and execute a callback function after returning.
$ ("# divResult"). load ("../ data / AjaxGetMethod.aspx", {"param": "btnAjaxCallBack_click"}, function (responseText, textStatus, XMLHttpRequest)
{
responseText = "Add in the CallBack Function! <br/>" + responseText
$ ("# divResult"). html (responseText); // or: $ (this) .html (responseText);
});
});
$ ("# btnAjaxFiltHtml"). click (function (event)
{
// Send a Get request to filter out the item "Anshan" from the results
$ ("# divResult"). load ("../ data / AjaxGetCityInfo.aspx? resultType = html" + "× tamp =" + (new Date ()). getTime () + "ul> li: not (: contains ('Anshan')) ");
});
})
</ script>
</ head>
<body>
<button id = "btnAjaxGet"> Perform Get Request with Load </ button> <br />
<button id = "btnAjaxPost"> Perform a Post request using Load </ button> <br />
<button id = "btnAjaxCallBack"> Use the Load method with a callback function </ button> <br />
<button id = "btnAjaxFiltHtml"> Use selector to filter returned HTML content </ button>
<br />
<div id = "divResult"> </ div>
</ body>
</ html>
The above example shows how to use the Load method.
Tip: We need to keep an eye on the browser cache and add a timestamp parameter (NET Date ()) When using the Get method. GetTime () to ensure that each URL is sent differently, you can avoid browser caching.
tip: When you add a space after the URL parameter, such as "", there will be an "unrecognized symbol" error, and the request can be sent normally. However, the HTML cannot be loaded into the DOM. After deletion, the problem is resolved.
2.jquery.get (URL, [data], [callback], [type])
Returns: XMLHttpRequest
Description
Loads information through a remote HTTP GET request.
This is a simple GET request function to replace the complex $.ajax. Callback functions can be invoked when the request succeeds. If you need to perform a function when an error occurs, use $.ajax.
Explain:
This function sends a GET request, and parameters can be spliced directly in the URL, such as:
$.get (".. /data/ajaxgetmethod.aspx?param=btnajaxget_click ");
Or passed by the data parameter:
$.get ("Btnajaxget2_click"});
The data parameter is automatically added to the requested URL when the effect is the same in both ways
If a parameter in the URL is passed by the data parameter, the parameter of the same name is 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 returned, Teststatus represents the status code, possibly the following value:
"Timeout", "error", "Notmodified", "Success", "ParserError"
This in the callback function is the reference that gets the options object. For a variety of descriptions of options, see:
Http://docs.jquery.com/Ajax/jQuery.ajax
The type parameter refers to the kind of data that may be the following value:
"XML", "HTML", "script", "JSON", "Jsonp", "text".
The default is "HTML."
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 for other domains, such as "myurl?callback=?", by using a callback function in JSONP form. Will jQuery be replaced automatically? To the correct function name to execute the callback function.
Note: The code after this line will execute before the callback function executes.
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 side is as follows:
[{""pkid"":""0997"",""ProvinceId"":""XJ"",""CityName"":""阿克苏"",""CityNameEn"":""Akesu"",""PostCode"":""843000"",""isHotCity"":false},
{""pkid"":""0412"",""ProvinceId"":""LN"",""CityName"":""鞍山"",""CityNameEn"":""Anshan"",""PostCode"":""114000"",""isHotCity"":false}]
In the example I return hungry is an array that uses data.length to get the number of elements of an array, data[0] to access the first element, Data[0]. CityName accesses the CityName property of the first element.
4.jquery.getscript (URL, [callback])
Returns: XMLHttpRequest
Equivalent to: Jquery.get (URL, null, [callback], "script")
Description
Loads and executes a JavaScript file through an HTTP GET request.
Before the JQuery 1.2 version, Getscript can only invoke the same domain JS file. 1.2, you can invoke JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you add a script by getscript, add the delay function.
Explain:
When I used the Dojo class library, the official default file does not support Cross-domain and eventually I quit using Dojo (although I found a cross-domain version on the web, it wasn't perfect). So I'm particularly focused on the core implementation and use of this function.
First understand the jquery internal implementation of this function, still using the Get function, all of the Ajax functions of jquery include the Jquery.ajax (), and the Getscript will pass in the type parameter with the value "script". Finally, the request to type for script in the AJAX function is handled as follows:
var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script");
script.src = s.url;
The code above dynamically creates a script statement block and adds it to the head:
Head.appendchild (script);
When the script is loaded, and then removed from the 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 Cross-domain access and multiple browser support for this function. Here is the result:
|
IE6 |
FireFox |
Attention matters |
Non-cross-domain reference JS |
Pass |
Pass |
Both data and textstatus in the callback function are available |
Cross-domain Reference JS |
Pass |
Pass |
Both data and textstatus in the callback function are 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
Loads information through a remote HTTP POST request.
This is a simple POST request function to replace the complex $.ajax. Callback functions can be invoked when the request succeeds. If you need to perform a function when an error occurs, use $.ajax.
Explain:
The exact usage is the same as get, except that the Submit method is changed from "Get" to "POST".
6. Jquery.ajax (Options)
Returns: XMLHttpRequest
Description
Load remote data through an HTTP request.
JQuery bottom AJAX implementation. Simple and easy-to-use high-level implementation see $.get, $.post, etc.
$.ajax () returns the XMLHttpRequest object that it created. In most cases you do not need to manipulate the object directly, but in special cases you can use it to manually terminate the request.
$.ajax () has only one parameter: The parameter Key/value object, which contains the configuration and callback function information. Detailed parameter options see below.
Note: If you specify the DataType option, make sure that the server returns the correct MIME information (such as the XML return "Text/xml"). The wrong MIME type can cause unpredictable errors. See Specifying the Data Type for AJAX Requests.
Note: If datatype is set to script, all post requests that are remote (not under the same domain name) will be converted to get requests. (because it will be loaded using the DOM's script tag)
In JQuery 1.2, you can load JSON data across domains and use it to set the data type to JSONP. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function. When the data type is set to "Jsonp", JQuery automatically invokes the callback function.
Explanation:
This is the core function of Ajax in jquery, which is called at the end of all functions that send AJAX requests. The options parameter supports a number of parameters that you can use to fully control the AJAX request. The This object in the Ajax callback function is also the options object.
Because the most commonly used or simplified get and post functions, so here is no detailed explanation of the options parameters. Options parameter documentation see:
Http://docs.jquery.com/Ajax/jQuery.ajax
Five. Ajax related functions.
jquery provides a number of related functions to assist Ajax functions.
1. jquery.ajaxsetup (options)
No return value
Description:
Sets the global AJAX default options option.
Explanation:
Sometimes we want to set the default behavior for all AJAX properties on the page. You can then use this function to set the options option, and then the default options for all AJAX requests will be changed.
The options is an object that can be set to the properties please this connection: Http://docs.jquery.com/Ajax/jQuery.ajax
For example, when the page loads, I use the following code to set the default option options for Ajax:
$.ajaxSetup({
url: "../data/AjaxGetMethod.aspx",
data: { "param": "ziqiu.zhang" },
global: false,
type: "POST",
success: function(data, textStatus) { $("#divResult").html(data); }
});
The code above sets the basic data required for an AJAX request: Request URL, parameter, request type, and successful callback function.
We can then send AJAX requests using a parameterless get (), post () or Ajax () method. The complete sample code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> jQuery Ajax-Load </ title>
<script type = "text / javascript" src = "../ scripts / jquery-1.3.2-vsdoc2.js"> </ script>
<script type = "text / javascript">
$ (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"});});
});
</ script>
</ head>
<body>
<button id = "btnAjax"> Call ajax () method without passing parameters </ button> <br />
<button id = "btnGet"> Call the get () method without passing parameters </ button> <br />
<button id = "btnPost"> Call the post () method without passing parameters </ button> <br />
<button id = "btnGet2"> call get () method with parameters, use global default callback function </ button> <br />
<br />
<div id = "divResult"> </ div>
</ body>
</ html>
Note When you use the Get () or post () method, except that the type parameter will be overridden as "got" or "post," other parameters, as long as they are not passed, are using the default global option. If an option is passed, such as when the last button passes the URL and the parameter, the call is based on the passed option. Options that are not passed, such as callback functions, or values are set using global option.
2.Serialize ()
Returns: String
Description:
The Sequence table table content is a string that is used for Ajax requests.
Serialization is most commonly used when sending form data to the server side. The serialized data is a standard format that can be supported by almost all but server-side.
In order to work as normally as possible, the form fields that are serialized require the name attribute, and only one Eid cannot work.
Write the Name property like this:
<IDnametype
Explain:
The serialize () function is spliced into a string of form objects in the form that will be sent to the server. Easy to get form data when we send with Ajax. This and a from when committing from the Get method automatically puts the name/value of the Form object on the URL to commit almost.
such as a form:
The generated string is:single=single¶m=multiple¶m=multiple3&check=check2&radio=radio1
Hint: code See chapter6\7-serialize.htm
3.Serializearray ()
Returns: Array<object>
Description
The serialized Table element (similar to the '. Serialize () ' method) returns the JSON data structure.
Note that this method returns a JSON object rather than a JSON string. You need to use Plug-ins or Third-party libraries for string manipulation.
Explain:
I'm disappointed to see the documentation, and I get a JSON object using this function, but jquery doesn't provide a way to convert a JSON object to a JSON string.
No suitable JSON compilers were found on the JSON web site, and the Jquery.json jquery plugin was selected at the end:
http://code.google.com/p/jquery-json/
It is exceptionally simple 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
With the Serializearray () and 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:
<! DOCTYPE html PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> jQuery Ajax-AjaxEvent </ title>
<script type = "text / javascript" src = "../ scripts / jquery-1.3.2.min.js"> </ script>
<script type = "text / javascript">
$ (document) .ready (function ()
{
$ ("# btnAjax"). bind ("click", function (event)
{
$ .get ("../ data / AjaxGetMethod.aspx");
})
$ ("# divResult"). ajaxComplete (function (evt, request, settings) {$ (this) .append ('<div> ajaxComplete </ div>');})
$ ("# divResult"). ajaxError (function (evt, request, settings) {$ (this) .append ('<div> ajaxError </ div>');})
$ ("# divResult"). ajaxSend (function (evt, request, settings) {$ (this) .append ('<div> ajaxSend </ div>');})
$ ("# divResult"). ajaxStart (function () {$ (this) .append ('<div> ajaxStart </ div>');})
$ ("# divResult"). ajaxStop (function () {$ (this) .append ('<div> ajaxStop </ div>');})
$ ("# divResult"). ajaxSuccess (function (evt, request, settings) {$ (this) .append ('<div> ajaxSuccess </ div>');})
});
</ script>
</ head>
<body>
<br /> <button id = "btnAjax"> Send an Ajax request </ button> <br/>
<div id = "divResult"> </ div>
</ body>
</ html>
Six. Global AJAX events
In Jquery.ajaxsetup (options), there is a global property in the Options parameter property:
Global
Type: boolean value
Default value: True
Description: whether to trigger global AJAX events.
This property is used to set whether the global Ajax event is triggered. Global AJAX events are a series of events that occur with AJAX requests. The main events are as follows:
Name |
Description |
Ajaxcomplete (callback) |
Execute function when AJAX request completes |
Ajaxerror (callback) |
Execute function when an AJAX request has an error |
Ajaxsend (callback) |
AJAX request execution function before sending |
Ajaxstart (callback) |
Execute function at start of AJAX request |
Ajaxstop (callback) |
Execute function at end of AJAX request |
Ajaxsuccess (callback) |
Execute function when AJAX request succeeds |
Use an example to explain the order in which each event is triggered:
<!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <Html xmlns= "Http://www.w3.org/1999/xhtml"> <Head> <Title>JQuery ajax-ajaxevent</Title> <Script Type= "Text/javascript" Src=".. /scripts/jquery-1.3.2.min.js "></Script><script type="Text/javascript"> $ (document) Ready (function() { $("#btnAjax"). Bind ("Click",function(Event) {$.get (".. /data/ajaxgetmethod.aspx "); }) $("#divResult"). Ajaxcomplete (function(evt, request, settings) { $(This). Append (' <div>ajaxComplete</div> '); }) $("#divResult"). Ajaxerror (function(evt, request, settings) { $(This). Append (' <div>ajaxError</div> '); }) $("#divResult"). Ajaxsend (function(evt, request, settings) { $(This). Append (' <div>ajaxSend</div> '); }) $("#divResult"). Ajaxstart (function() { $(This). Append (' <div>ajaxStart</div> '); }) $("#divResult"). Ajaxstop (function() { $(This). Append (' <div>ajaxStop</div> '); }) $("#divResult"). Ajaxsuccess (function(evt, request, settings) { $(This). Append (' <div>ajaxSuccess</div> '); }) });</Script> </head> body> <br / ><button id= "Btnajax" > Send Ajax request </button><br/> <div id= " Divresult "div> </< span class= "HTML" >body> </html
The result is as shown in figure:
We can cancel the triggering of global Ajax events by setting the global property of the default options to False.
Seven. 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
To get the param parameter using the server-side method:
if (!String.IsNullOrEmpty(HttpContext.Current.Request["Param"]))
{
param = HttpContext.Current.Request["Param"];
}
Get param at this point is a string that separates multiple values with ",":
Eight. Summary
This article describes how to use jquery to implement AJAX functionality. The gradient Ajax methods used to send AJAX requests, such as load, get, Getjson, and post, are not overly described in the core AJAX approach, and are largely controlled by the configuration of complex parameters to achieve full control of AJAX requests. It also explains Ajax's auxiliary functions, such as the Serialize () method used to serialize the form object to a string, which is used to serialize the form object to the Serializearray () method of the JSON object. These are useful for using scripting to get data implementations and server-side interactions, and JSON-formatted data frees us from confusing attribute strings when dealing with large object programming.
jquery also provides a special event for entering global AJAX events, and can set these events on an object, which are invoked at each lifecycle of sending an AJAX request, and you can turn global events on or off by modifying the global property of the default Options object.
At present, this series of articles in the stage of intensive creation. So there's no time to rearrange the code and article examples. Here is the code download for this chapter, but it contains all the examples that have not been sorted before, please download and look at the Chapter6 folder, which is all the examples in this chapter:
Http://xiazai.jb51.net/201101/yuanma/Code-jQueryStudy.rar