jquery is really a nice lightweight JS framework that can help us quickly develop JS applications and, to some extent, change our habit of writing JavaScript code. Cut the crap, go straight to the point, let's take a look at some simple methods that encapsulate the Jquery.ajax () to make it easier for us to use, and of course, if you want to deal with complex logic, you need to use Jquery.ajax ().1. Load(URL, [data], [callback]): Loads the remote HTML file code and inserts it into the DOM.URL(String): The URL address of the requested HTML page.Data(MAP): (optional parameter) Key/value data sent to the server.Callback(Callback): (optional parameter) a callback function that does not need to be success when the request completes. This method is passed by default using Get method, and is automatically converted to post if the [data] parameter is passed in. 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 is 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 refers to the current DOM object, that is $ (". Ajax.load") [0]
// alert (responsetext);//Request returned content
//alert (textstatus);/Request Status: Success,error
//alert (XMLHttpRequest); XMLHttpRequest Object
}); The results are displayed here.Note:Do not know why the URL write absolute path under FF will be wrong, know the trouble to tell. The following get () and post () examples use an absolute path, so you will go wrong under FF and you will not see the results returned. The Get () and post () examples are called across domains, and they are found to be not able to get results, so the run button is removed.2. Jquery.get(URL, [data], [callback]): Use Get method for asynchronous request parameters:URL(String): The URL address at which the request is sent.Data(MAP): (optional) The data to be sent to the server, expressed as a Key/value key-value pair, is appended to the request URL as querystring.Callback(function): (optional) the callback function (which is invoked only if the return state of the response is success) when loading succeeds. 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. Sample code: $.get ("./ajax.aspx", {Action: "Get", Name: "Lulu"}, function (data, textstatus) {
//returned data can be xmldoc, jsonobj, HTML, Text, and so on.
This Here is the option configuration information for the AJAX request, please refer to Figure
Alert (data) below.
Alert (Textstatus),//Request status: Success,error, and so on. Of course, the error is not captured here, because the error will not run the callback function
//alert (this);
Click Send Request: This in the Jquery.get () callback function, pointing to the option configuration information for the AJAX request:3. Jquery.post(URL, [data], [callback], [type]): Use the Post method for asynchronous request parameters:URL(String): The URL address at which the request is sent.Data(MAP): (optional) The data to be sent to the server, expressed as a Key/value key-value pair.Callback(function): (optional) the callback function (which is invoked only if the return state of the response is success) when loading succeeds.type(String): (optional) The official description is: Type of data to is sent. The type that should actually be requested for the client (Json,xml, etc.) 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. 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, HT ML, text, and so on.
This For this AJAX-requested option configuration information, refer to the This alert (Data.result) mentioned in Jquery.get ()
;
}, "JSON"; Click Submit: The format requested here is "JSON": if you set the requested format as "JSON", you are not setting the Response back ContentType as: Response.ContentType = "application/ JSON "; Then you will not be able to capture the returned data. Note that alert (data.result); With the Accept header "JSON" set, the data returned here is an object that does not need to be converted to an object with eval ().4. Jquery.getscript(URL, [callback]): Load and execute a JavaScript file with a Get-mode request.Parameters URL(String): The address of the JS file to be loaded.Callback(function): (optional) After successfully loading the callback function. 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. This method can be used for example, when only the editor focus () to load the editor required JS file. Here are some sample code: Load and execute test.js.jQuery Code:$.getscript ("Test.js"); Load and execute ajaxevent.js, and then display the information successfully.jQuery Code: $.getscript ("Ajaxevent.js", function () {
alert ("Ajaxevent.js loading completed and execution completed.) Click the Get or Post button above to see what's different. ");
}); After loading, please click on the load request above to see what the difference is.jQuery Ajax EventsAjax requests produce a number of different events, and we can subscribe to these events and process our logic in them. There are two kinds of Ajax events in jquery: Local events and global events.Local Eventsis defined within the method at each AJAX request, for example:$.ajax ({
beforesend:function () {
//Handle the Beforesend event
},
complete:function () {
// Handle the Complete Event
}
//...
}; Global EventsEvery time an AJAX request is triggered, it broadcasts to all elements in the DOM, and the script loaded in the Getscript () example above is a 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 at a specific request, as long as you set the global option:$.ajax ({
URL: "test.html",
global:false,//disables global Ajax events.
) // ...
}); The following is a complete list of Ajax events that are officially given by jquery:Ajaxstart(Global Event) This event is broadcast if a AJAX request is started and no other AJAX requests are currently running.Beforesend(Local Event) This event, which are triggered before an Ajax request is started, allows your to modify the XMLHttpRequest object (setting Additional headers, if need be.)Ajaxsend(Global Event) This global event was 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 and no errors with the data).ajaxsuccess(Global Event) This event is also only called if the request was successful.Error(Local Event) This is the ' only called if ' occurred with the ' request (you can never have both an error and a success callback W ith 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'll always receive a complete callback, even for synchronous requests.Ajaxcomplete(Global Event) This event behaves the same as the complete event and would be triggered every time of Ajax request finishes.Ajaxstop(Global Event) This global event are triggered if there are no more Ajax requests being processed. For specific global events, refer to the API documentation. OK, here's what I'll say. The most powerful Ajax request method in jquery is $.ajax ();Jquery.ajax(options): Load remote Data via HTTP request This is the underlying AJAX implementation of jquery. 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.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. When setting the DataType type ' 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 the configuration and callback function information. Detailed parameter options see below. 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. (This I don't know very well) parameter list:
Name of parameter |
Type |
Describe |
Url |
String |
(Default: Current page address) sends the requested address. |
Type |
String |
(Default: "Get") Request method ("POST" or "get"), default to "get". Note: Other HTTP request methods, such as put and DELETE, are also available, but only partially supported by browsers. |
Timeout |
Number |
Sets the request timeout (in milliseconds). This setting overrides the global setting. |
Async |
Boolean |
(Default: TRUE) The default setting is that all requests are asynchronous requests. If you need to send a sync request, set this option to false. Note that the synchronization request will lock the browser and the user's other actions must wait for the request to complete before it can be executed. |
Beforesend |
Function |
You 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
} |
Cache |
Boolean |
(default: TRUE) JQuery 1.2 new functionality, set to false will not load request information from the browser cache. |
Complete |
Function |
The callback function (called when the request succeeds or fails) after the request completes. Parameters: XMLHttpRequest Object, Success message string.
function (XMLHttpRequest, textstatus) {this
;//The options for this AJAX request
} |
ContentType |
String |
(Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. Default values are appropriate for most applications. |
Data |
Object, String |
Data sent to the server. is automatically converted to the request string format. The GET request is appended to the URL. View the ProcessData option description to prevent this automatic conversion. Must be in the Key/value format. If you are an array, JQuery will automatically correspond to the same name for different values. As {foo:["bar1", "Bar2"]} is converted to ' &foo=bar1&foo=bar2 '. |
DataType |
String |
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 packet MIME information and pass as a callback function argument, available values: "XML": Returns an XML document that can be processed with jQuery. HTML: Returns plain text HTML information, including script elements. Script: Returns the plain text JavaScript code. Results are not automatically cached. "JSON": Returns JSON data. "JSONP": Jsonp format. 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. |
Error |
Function |
(Default: Automatic judgment (XML or HTML)) This method is called when a request fails. This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being caught.
function (XMLHttpRequest, textstatus, Errorthrown) {
//typically Textstatus and Errorthown only one of them has a value of this
; Options for this AJAX request
} |
Global |
Boolean |
(default: TRUE) triggers a global AJAX event. Setting to FALSE will not trigger global AJAX events, such as Ajaxstart or Ajaxstop. Can be used to control different AJAX events |
Ifmodified |
Boolean |
(default: false) gets new data only when the server data changes. Use HTTP packet last-modified header information to determine. |
ProcessData |
Boolean |
(default: TRUE) by default, the data sent is converted to an object (technically not a 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. |
Success |
Function |
callback function after successful request. This method has two parameters: the server returns the data, returns the status
function (data, textstatus) {
//data could be xmldoc, jsonobj, HTML, text, etc ...
This The options for this AJAX request
} |
Here are a few Ajax event parameters:Beforesend,Success,complete, error. We can define these events to deal well with each of our AJAX requests. Notice that this in these AJAX events is the information about the options for the Ajax request (refer to the picture of this when you say Get () method). Read the argument list carefully, and if you want to use jquery for AJAX development, you need to be familiar with these parameters.sample code to get the title of the article on the home page of the blog: $.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 option. Set AJAX request default address is "/xmlhttp/", prohibit triggering global Ajax event, use POST instead of default get method. Subsequent AJAX requests no longer have any option parameters set.jQuery Code: $.ajaxsetup ({
URL: "/xmlhttp/",
global:false,
type: "POST"
});
$.ajax ({data:mydata}); serialize () and Serializearray ()Serialize (): Sequence table table contents are strings. Serializearray (): Serializes the Table element (similar to the '. Serialize () ' method) to return the JSON data structure. Example: HTML code:<p id= "Results" ><b>Results:b> p>
<form>
<select name= "single" >
< option>singleoption>
<option>Single2option>
select>
<select name= "multiple" multiple= "multiple" >
<option selected= "selected" >Multipleoption>
<option> multiple2option>
<option selected= "selected" >Multiple3option>
select><br/>
<input type= "checkbox" name= "Check" value= "Check1"/> check1 <input type=
"checkbox" name= "Check" value= " Check2 "
checked=" checked "/> check2 <input type=" Radio "name=" Radio "value=" Radio1 "checked="
Checked "/> radio1 <input type=" Radio "name=" Radio "value=" Radio2 "/>" Radio2
Serializearray () The result is: Some resourcesA jquery ajax form plug-in: [Url]http://www.malsup.com/jquery/form/[/url] A site dedicated to generating loading images: [url]http:// Ajaxload.info/[/url] People think those loading more dazzling can be here to bask, convenient for everyone to take, quack |