Several ways to request Ajax in jquery

Source: Internet
Author: User
Tags getscript browser cache

1. Load(URL, [data], [callback]): Load the remote HTML file code and insert 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) when the request is complete (no need to be success.) of the callback function. This method is passed by default using GET, 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 in the DOM. Syntax such as "URL #some > selector". This method makes it easy to dynamically load some HTML files, such as forms. Example code:
$ (". Ajax.load"). Load ("[Url]http://www.cnblogs.com/qleelulu/archive/2008/03/30/1130270.html[/url]. Post", function (ResponseText, textstatus, XMLHttpRequest) {this;//Here is a pointer to the current DOM object, which 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 error, know the trouble to tell under. The Get () and post () examples below use an absolute path, so you will get an error under FF and you will not see the results returned.The get () and post () examples are all cross-domain calls, and there is no way to get the results after the transmission, so the run button is removed. 2. Jquery.get(URL, [data], [callback]): Use Get method to make asynchronous request
parameter: URL (String): The URL address of the sending request. Data (MAP): (optional) data to be sent to the server, expressed as a Key/value key-value pair, will be appended to the request URL as querystring. Callback (function): (optional) The callback function when loading succeeds (the method is called only if the return state of response is success).
This is a simple GET request feature to replace complex $.ajax. The callback function can be called when the request succeeds. If you need to execute the function on error, use $.ajax. Example code:
$.get ("./ajax.aspx", {Action: "Get", Name: "Lulu"}, function (data, textstatus) {///The data returned can be xmldoc, jsonobj, HTML, text, And so on. this; Here this point is the option configuration information for the AJAX request, please refer to alert (data),//alert (Textstatus),//Request status: Success,error, etc.
Of course, the error is not caught here, because the error does not run the callback function at all//alert (this);});
Click Send Request: The This in the Jquery.get () callback function, which points to the option configuration information for the AJAX request: 3. Jquery.post(URL, [data], [callback], [type]): Use post to make asynchronous requests
parameter: URL (String): The URL address of the sending request. Data (MAP): (optional) data to be sent to the server, expressed as a Key/value key-value pair. Callback (function): (optional) The callback function when loading succeeds (the method is called only if the return state of response is success).  type (String): (optional) The official description is: Type of data to be 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. The callback function can be called when the request succeeds. If you need to execute the function on error, use $.ajax. Example 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, HTML, text, And so on.//this; For the option configuration information for this Ajax request, refer to Jquery.get () Thisalert (Data.result);}, "JSON");
Click Submit: Here set the request format as "JSON": if you set the request format to "JSON", at this time you do not set Response back ContentType: Response.ContentType = "application/ JSON "; Then you will not be able to capture the returned data. Note that alert (data.result); Because the Accept header is set to "JSON", the data returned here is an object and does not need to be converted to an object using eval (). 4. Jquery.getscript(URL, [callback]): Request to load and execute a JavaScript file via GET mode .
parameter URL (String): The address of the JS file to be loaded. Callback (function): (optional) The post-load callback function is successfully loaded.
Before the JQuery 1.2 version, GetScript can only invoke the same domain JS file. 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you join the script through GetScript, add the delay function. This method can be used for example, when only the editor focus () to load the editor needs the JS file. Here are some sample code:

Load and execute the test.js.

jQuery Code:$.getscript ("Test.js"), load and execute ajaxevent.js, display information after success. jQuery Code:
$.getscript ("Ajaxevent.js", function () {alert ("Ajaxevent.js") completes and executes. Do you click the Get or Post button above to see what's different? ");});
After loading, please re-click on the load request above to see what is different. jQuery Ajax EventsAjax requests generate a number of different events, and we can subscribe to these events and handle our logic in them. There are two types of Ajax events in jquery: Local events and global events. Local Eventsis defined in 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 the 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 () {   
We can disable global events on 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 was broadcast if an AJAX request was started and no other AJAX requests was currently running.
    • Beforesend (Local Event)
      This event, which was triggered before an Ajax request was started, allows you to modify the XMLHttpRequest object (setting Additional headers, if need be.)
    • Ajaxsend (Global Event)
      This global event is also triggered before, the request is run.
    • Success (Local Event)
      This event is a called if the request was successful (no errors from the server, no errors with the data).
    • ajaxsuccess (Global Event)
      This event is also only called if the request was successful.
    • Error (Local Event)
      This event was only called if an error occurred with the request (you can never has 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 a 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 an Ajax request finishes.
  • Ajaxstop(Global Event)
    This global event was triggered if there is no more Ajax requests being processed. Refer to the API documentation for specific global events.
    Well, here's how the most powerful Ajax request method in jquery is $.ajax (); jquery.ajax(options): Loading remote data over HTTP requestsThis is the underlying AJAX implementation of jquery. Easy to use high-level implementation see $.get, $.post and so on. $.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 terminate the request manually.Note:If you specify the DataType option, make sure that the server returns the correct MIME information (such as XML returns "Text/xml"). The wrong MIME type can cause unpredictable errors. See Specifying the Data Type for AJAX requests.
    When the datatype type "script" is set, all remote (not in the same domain) Post request is 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 are shown below. In JQuery 1.2, you can load JSON data across domains and set the data type to JSONP when used. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function. When the data type is set to "Jsonp", JQuery automatically calls the callback function. (This I don't quite understand) parameter list:
    Name of parameter Type Describe
    Url String (Default: Current page address) sends the requested address.
    Type String (Default: "Get") The Request method ("POST" or "get"), the default is "get". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it.
    Timeout Number Sets the request time-out (in milliseconds). This setting overrides the global settings.
    Async Boolean (default: TRUE) by default, all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the sync 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 feature, set to False will not load the request information from the browser cache.
    Complete Function The callback function after the request completes (called when the request succeeds or fails). Parameters: XMLHttpRequest Object, Success information 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. The default values are suitable for most applications.
    Data Object,
    String
    Data sent to the server. is automatically converted to the request string format. The GET request will be appended to the URL. View the ProcessData option description to disallow this automatic conversion. Must be a key/value format. If an array, JQuery automatically corresponds to the same name for the different values. such as {foo:["bar1", "Bar2"]} converted to ' &foo=bar1&foo=bar2 '.
    DataType String Expected data type returned by the server. If not specified, jquery automatically returns Responsexml or ResponseText based on the HTTP packet MIME information and is passed as a callback function parameter, with the available values: "XML": Returns an XML document that can be processed with jQuery. HTML: Returns plain text HTML information, including the script element. "Script": Returns plain text JavaScript code. Results are not automatically cached. "JSON": Returns the JSON data. "JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function.
    Error Function (Default: This method is called when a request for automatic judgment (XML or HTML) fails.) This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being captured.
    function (XMLHttpRequest, textstatus, Errorthrown) {  //normally textstatus and Errorthown only one has the value of this   ; Options for this AJAX request}
    Global Boolean (default: TRUE) whether to trigger global AJAX events. 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) to get new data only when the server data changes. Use the HTTP packet last-modified header information to determine.
    ProcessData Boolean (default: TRUE) by default, the sent data 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 The callback function after the request succeeds. This method has two parameters: the server returns 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:BeforesendSuccessComplete , error. We can define these events to handle each of our AJAX requests well. Note that these AJAX events ThisAre the option information that points to the Ajax request (refer to the picture of this when you say the Get () method).
    Please read the above parameter list carefully, if you want to use jquery for Ajax development, then these parameters you must be familiar with. Sample code to get the blog home page of the article title:
    $.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: Set global AJAX default options. Set the default address of the AJAX request to "/xmlhttp/", prohibit triggering of global Ajax events, use POST instead of the default GET method. Subsequent AJAX requests no longer set any option parameters.jQuery Code:
    $.ajaxsetup ({  URL: "/xmlhttp/",  global:false,  type: "POST"}); $.ajax ({data:mydata});
    serialize () and Serializearray ()Serialize (): The table contents of the sequence table are strings. Serializearray (): Serializes a tabular element (similar to the ". Serialize ()" method) to return the data of 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  
    Serializearray () The result is:Some resources A jquery ajax form plugin: [Url]http://www.malsup.com/jquery/form/[/url] A site that specifically generates loading images: [url]http:// ajaxload.info/[/url]   

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.