JQuery Ajax and jqueryajax

Source: Internet
Author: User
Tags getscript

JQuery Ajax and jqueryajax

JQuery is indeed a very lightweight JS framework that can help us quickly develop JS applications and change the habit of writing JavaScript code to a certain extent.

Let's talk nonsense and go straight to the question. Let's take a look at some simple methods, all of which are for jQuery. ajax () is encapsulated to facilitate our use of the method. Of course, if you want to process complicated logic, you still need to use jQuery. ajax () (this will be mentioned later ).

1. load(Url, [data], [callback]): loads remote HTML file code and inserts it into the DOM.

Url(String): the URL of the requested HTML page.

Data(Map): (optional) key/value data sent to the server.

Callback(Callback): (optional) Callback function when the request is completed (success is not required.

By default, this method uses the GET method to pass data. If the [data] parameter passes data in, it is automatically converted to the POST method. In jQuery 1.2, you can specify a selector to filter loaded HTML documents. In DOM, only filtered HTML code is inserted. The syntax is like "url # some> selector ".

This method can easily dynamically load HTML files, such as forms.

Sample Code:

$ (". Ajax. load"). load ("http://www.cnblogs.com/yeer/archive/2009/06/10/1500682.html. post ",
Function (responseText, textStatus, XMLHttpRequest ){
This; // here this points to the current DOM object, that is, $ (". ajax. load") [0]
// Alert (responseText); // content returned by the request // alert (textStatus); // Request status: success, error // alert (XMLHttpRequest ); // XMLHttpRequest object });

 

The difference between empty () and remove () in jquery is that empty () and remove ([expr]) can be used to remove a specified element. If you can observe the effect carefully, you can find out. Empty () removes only all child nodes in the specified element, and takes $ ("p "). for empty (), he just removed the text in <p> dsfsd </p> and left <p> </p>, still keep its position in the dom.
Remove ([expr]) is to delete it from the dom without retaining its position.
Example:
<P> Hello </p>
World
<P> welcome </p>
Run $ ("p"). empty () and the result is
<P> </p>
World
<P> </p>

Run $ ("p"). remove () and the result is
World

Note:I don't know why an error occurs when the absolute URL write path is in FF. Please let me know. The following get () and post () Examples use absolute paths, so you will encounter errors in FF and will not see the returned results. The get () and post () Examples are all cross-origin calls, and the results cannot be obtained after being uploaded. Therefore, the run button is removed.

2. jQuery. get(Url, [data], [callback]): Use the GET Method for asynchronous requests.

Parameters:

Url(String): the URL of the request.

Data(Map): (optional) data to be sent to the server, which is expressed in Key/value pairs and will be appended to the request URL as QueryString.

Callback(Function): (optional) callback Function when loading is successful (this method is called only when the Response returns success ).

This is a simple GET request function to replace complex $. ajax. You can call the callback function when the request is successful. To execute a function when an error occurs, use $. ajax. Sample Code:

$. Get ("./Ajax. aspx", {Action: "get", Name: "lulu"}, function (data, textStatus ){
// The returned data can be xmlDoc, jsonObj, html, text, and so on. this; // here this points to the configuration information of the Ajax request options. See alert (data );
// Alert (textStatus); // Request status: success, error, and so on.
Of course, no error is caught here, because the callback function // alert (this);} is not executed during the error process );});

Click Send request:

This in the jQuery. get () callback function points to the option configuration information of the Ajax request:

 

3. jQuery. post(Url, [data], [callback], [type]): Use the POST method for asynchronous requests.

 

Parameters:

Url(String): the URL of the request.

Data(Map): (optional) data to be sent to the server, expressed in Key/value pairs.

Callback(Function): (optional) callback Function when loading is successful (this method is called only when the Response returns success ).

Type(String): (optional) the official description is: Type of data to be sent. In fact, it should be the client request type (JSON, XML, and so on)

This is a simple POST Request function to replace complex $. ajax. You can call the callback function when the request is successful. To execute 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, html, text, and so on. // this; // configure the options for this Ajax request. For more information, see jQuery. thisalert (data. result );
}, "Json ");

Click to submit:

The request format is set to "json ":

If you set the request format to "json", you have not set the ContentType returned by Response to: Response. contentType = "application/json"; then you cannot capture the returned data.

Note that alert (data. result); because the Accept header is set to "json", the returned data is an object and does not need to be converted to an object using eval.

 

4. jQuery. getScript(Url, [callback]): load and execute a JavaScript file using GET requests.

Parameters

Url(String): the URL of the JS file to be loaded.

Callback(Function): (optional) callback Function after successful loading.

Before jQuery 1.2, getScript can only call JS files in the same domain. 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier versions cannot execute scripts simultaneously in the global scope. If you use getScript to add a script, add the latency function.

This method can be used, for example, to load the JS file required by the editor only when the editor focus (). See some sample code below:

Load and execute test. js.

JQuery code:

$. GetScript ("test. js ");

Load and execute AjaxEvent. js. The information is displayed after successful execution.

JQuery code:

$. GetScript ("AjaxEvent. js", function (){
Alert ("AjaxEvent. js loading is complete and execution is complete. You can click the Get or Post button above to see what is different? ");
});

 

After loading, click the Load request above to see what is different.

JQuery Ajax events

Ajax requests Generate several different events. We can subscribe to these events and process our logic in them. There are two types of Ajax events in jQuery: local events and global events.

Local eventsIs defined in the method for each Ajax request, for example:

 $.ajax({
beforeSend: function(){
// Handle the beforeSend event},complete: function(){
// Handle the complete event}// ...});

Global eventsIt is triggered by every Ajax request. It broadcasts all elements to the DOM. The script loaded in the preceding getScript () example 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 in a specific request, as long as the global option is set:

$. Ajax ({
Url: "test.html ",
Global: false, // disable global Ajax events .//...});

The following is a complete list of Ajax events officially provided by jQuery:

  • AjaxStart(Global Event)
    This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.
    • BeforeSend(Local Event)
      This event, which is triggered before an Ajax request is 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 only 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 is only called if an error occurred with the request (you can never have both an error and a success callback with 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 will always receive a complete callback, even for synchronous requests.
    • AjaxComplete(Global Event)
      This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
  • AjaxStop(Global Event)
    This global event is triggered if there are no more Ajax requests being processed.

    For details about global events, refer to the API documentation.
    Well, let's start with jQuery's most powerful Ajax Request Method $. ajax ();

    JQuery. ajax(Options): Load remote data through HTTP requests

    This is the underlying AJAX Implementation of jQuery. For easy-to-use high-level implementation, see $. get, $. post, and so on.

    $. Ajax () returns the created XMLHttpRequest object. In most cases, you do not need to directly operate on this object, but in special cases it can be used to manually terminate the request.

    Note:If you specify the dataType option, make sure that the server returns the correct MIME information (for example, xml returns "text/xml "). Incorrect MIME types may cause unpredictable errors. See Specifying the Data Type for AJAX Requests.
    When the datatype type is set to 'script', all remote (not in the same domain) POST requests are switched to GET.

    $. Ajax () has only one parameter: The parameter key/value object, which contains information about various configurations and callback functions. For detailed Parameter options, see.

    In jQuery 1.2, you can load JSON data across domains. You need to set the data type to JSONP during use. When calling a function in the form of JSONP, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function. When the data type is set to "jsonp", jQuery automatically calls the callback function. (I don't quite understand this)

    Parameter List:

     

    Parameter Name Type Description
    Url String (Default: Current page address) the address of the request sent.
    Type String (Default: "GET") Request Method ("POST" or "GET"). The default value is "GET ". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but are only supported by some browsers.
    Timeout Number Set the request timeout (in milliseconds ). This setting overwrites the global setting.
    Async Boolean (Default: true) by default, all requests are asynchronous requests. To send a synchronization request, set this option to false. Note: The synchronous request locks the browser. Other operations can be performed only after the request is completed.
    BeforeSend Function Before sending a request, you can modify the function of the XMLHttpRequest object, for example, adding a custom HTTP header. The XMLHttpRequest object is a unique parameter.
    function (XMLHttpRequest) {
    this; // the options for this ajax request }
    Cache Boolean (Default: true) New jQuery 1.2 function. setting this parameter to false will not load request information from the browser cache.
    Complete Function Callback Function after the request is complete (called when the request is successful or fails ). Parameter: XMLHttpRequest object, success information string.
    function (XMLHttpRequest, textStatus) {
    this; // the options for this ajax request }
    ContentType String (Default: "application/x-www-form-urlencoded") Content Encoding type when sending information to the server. The default value is applicable to most applications.
    Data Object,
    String
    The data sent to the server. Will be automatically converted to the request string format. The GET request will be appended to the URL. View the description of the processData option to disable automatic conversion. It 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 '.
    DataType String

    Expected data type returned by the server. If this parameter is not specified, jQuery will automatically return responseXML or responseText Based on the MIME information of the HTTP package and pass it as a callback function parameter. Available values:

    "Xml": returns an XML document, which can be processed by jQuery.

    "Html": returns plain text HTML information, including script elements.

    "Script": returns plain text JavaScript code. Results are not automatically cached.

    "Json": Return JSON data.

    "Jsonp": JSONP format. When calling a function in the form of JSONP, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function.

    Error Function (Default: automatically determines (xml or html) This method is called when a request fails. This method has three parameters: XMLHttpRequest object, error message, and (possibly) captured error object.
    Function (XMLHttpRequest, textStatus, errorThrown ){
    // Generally, only one of textStatus and errorThown has the value this; // the options for this ajax request}
    Global Boolean (Default: true) Whether to trigger a global AJAX event. Setting false does not trigger global AJAX events, such as ajaxStart or ajaxStop. Can be used to control different Ajax events
    IfModified Boolean (Default: false) obtain new data only when the server data changes. Use the Last-Modified header information of the HTTP packet to determine.
    ProcessData Boolean (Default: true) by default, data sent is converted to an object (technically not a string) with the default content type "application/x-www-form-urlencoded ". If you want to send the DOM tree information or other information that does not want to be converted, set it to false.
    Success Function Callback Function after successful request. This method has two parameters: the server returns data and returns the status.
    function (data, textStatus) {
    // data could be xmlDoc, jsonObj, html, text, etc... this; // the options for this ajax request }

     

    Here are several Ajax event parameters:BeforeSend,Success,Complete, error.We can define these events to process every Ajax request. Note that this in these Ajax events points to the option Information of the Ajax request (see the image of this in the get () method ).
    Read the parameter list carefully. If you want to use jQuery for Ajax development, you must be familiar with these parameters.

    Sample Code to obtain the topic of the blog homepage:
    $. Ajax ({
    Type: "get ",
    Url: "http://www.cnblogs.com/rss ",
    BeforeSend: function (XMLHttpRequest ){
    // ShowLoading () ;}, success: function (data, textStatus ){
    $ (". Ajax. ajaxResult" ).html ("");
    $ ("Item", data). each (function (I, domEle ){
    $ (". Ajax. ajaxResult "). append ("<li>" + $ (domEle ). children ("title "). text () + "</li> ");
    });
    },
    Complete: function (XMLHttpRequest, textStatus ){
    // HideLoading () ;}, error: function (){
    // Handle request errors }});

     

  • The homepage article list is displayed.

     

     

    Others

    JQuery. ajaxSetup(Options): set global AJAX default options.

    Set the default address of an AJAX request to "/xmlhttp/". Do not trigger a global AJAX event. Use POST instead of the default GET method. No option parameters are set for subsequent AJAX requests.

    JQuery code:

    $.ajaxSetup({
    url: "/xmlhttp/",
    global: false,
    type: "POST"
    });
    $.ajax({ data: myData });

     

    Serialize () and serializeArray ()

    Serialize (): the content of the sequence table is a string.

    SerializeArray (): serialize table elements (similar to the '. serialize ()' method) to return JSON data structure data.

    Example:

    HTML code:

    <p id="results"><b>Results: </b> </p><form><select name="single"><option>Single</option><option>Single2</option></select><select name="multiple" multiple="multiple"><option selected="selected">Multiple</option><option>Multiple2</option><option selected="selected">Multiple3</option></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

    </form>
  • The result of serializeArray () is:

Related Article

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.