AJAX in JQuery

Source: Internet
Author: User
Tags getscript

AJAX in JQuery

Load () method

Load (url, [data], [callback])

The url is the address of the loaded page.

Data indicates the data sent to the server. The format is key/value.

Callback format: function (responseText, textStatus, XMLHttpRequest ){}

// ResponseText: Content returned by the request

// TextStatus: Request status: success, error, notmodified, and timeout

// XMLHttpRequest: XMLHttpRequest object

The load () method is automatically specified based on the parameter data. If no parameter is transmitted, the GET method is used; otherwise, the POST method is automatically converted.

$ ("# Div1 "). load ("jsp/feed. jsp ", // if it is" jsp/feed. jsp. filterClass "indicates to obtain all the elements of the class named filterClass on the jsp page {name: clf, age: 25 // tested. The variable name is enclosed by quotation marks, single quotation marks, and no quotation marks, values can be obtained in the backend. // if the value contains Chinese characters, the value must be encoded with encodeURI (), and then decoded with decodeURI () on the server side, such as // {name: encodeURI ($ ("# uName "). val (), "password": $ ("# uPassword "). val ()},}, // you can also use an array to pass values. {"attr []", ["clf", "25", "male"]} function () {$ ("# div2 "). text ("AJAX ");});

$("div").load("wrongname.xml",function(response,status,xhr){      if (status=="success")      {              $("div").html("
  
  
    "); $(response).find("artist").each(function(){ varitem_text = $(this).text(); $('
  1. ').html(item_text).appendTo('ol'); }); } else { $("div").html("Anerror occured:
    " + xhr.status + " " + xhr.statusText) } });

    GetJSON () method

    GetJSON (url, [data], [callback])

    Callback format: function (data, textStatus ){}

    Data is a returned json object.

    $.getJSON("test.js",{ name: "John", time: "2pm" }, function(json){  alert("JSON Data: " +json.users[3].name);});

    GetScript () method

    GetScript (url, [callback])

    The callback format is function (response, status)

    Response-contains the result data from the request

    Status-contains the Request status ("success", "notmodified", "error", "timeout" or "parsererror ")

    The script injected with this function is automatically executed.

    Get () method

    Get (url, data, callback (response, status, xhr), dataType)

    Possible types of ype: "xml", "html", "text", "script", "json", and "jsonp"

    The get () method loads information through a remote HTTPGET request.

    Post () method

    Post (url, data, callback (response, status, xhr), dataType)

    Similar to the get () method

    The get () method is not suitable for transmitting data with a large amount of data. At the same time, the historical request information is stored in the browser cache, which poses a certain risk () the method does not have this deficiency.

    Serialize () method

    The serialize () method creates a URL encoded text string by serializing the form value.

    You can select one or more form elements (such as input and/or text boxes) or form elements.

    Serialized values can be used in URL query strings when an AJAX request is generated.

     
     

    $('form').submit(function(){  alert($(this).serialize());  return false;});

    Output standard query string:

    A = 1 & B = 2 & c = 3 & d = 4 & e = 5

    Note: Only "successful controls" are serialized as strings. If the button is not used to submit a form, the value of the submit button is not serialized. To include the value of a form element in a sequence string, the element must use the name attribute. When multiple items in the form are selected, this method can pass only one value.

    Ajax () method

    1. url:

    It must be a String parameter (the current page address by default.

    2. type:

    The request method (post or get) is get by default. Note that other http request methods, such as put and delete, can also be used, but are only supported by some browsers.

    3. timeout:

    Set the request timeout time (in milliseconds) for a Number parameter ). This setting overwrites the global settings of the $. ajaxSetup () method.

    4. async:

    A Boolean parameter is required. The default value is true. 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.

    5. cache:

    A Boolean parameter is required. The default value is true. If dataType is set to script, the default value is false. If it is set to false, request information is not loaded from the browser cache.

    6. data:

    The data sent to the server must be of the Object or String type. If it is no longer a string, it is automatically converted to the string format. The get request will be appended to the url. To prevent this automatic conversion, you can view the processData option. The object must be in the key/value format. For example, {foo1: "bar1", foo2: "bar2"} is converted to & foo1 = bar1 & foo2 = bar2. 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.

    7. dataType:

    It must be a String parameter. The data type returned by the server is expected. 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. The available types are as follows:

    Xml: the XML document is returned and can be processed by JQuery.

    Html: returns plain text HTML information. The included script tag is executed when the DOM is inserted.

    Script: returns plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note that during remote requests (not in the same domain), all post requests will be converted to get requests.

    Json: Return JSON data.

    Jsonp: JSONP format. When a function is called in the form of SONP, such as myurl? Callback = ?, JQuery will automatically Replace the last "?" For the correct function name to execute the callback function.

    Text: returns a plain text string.

    8. beforeSend:

    A parameter of the Function type is required. Before sending a request, you can modify the Function of the XMLHttpRequest object, for example, adding a custom HTTP header. In beforeSend, if false is returned, the ajax request can be canceled. The XMLHttpRequest object is a unique parameter.

    Function (XMLHttpRequest) {this; // The options parameter passed when calling this ajax request}

    9. complete:

    A parameter of the Function type is required. The callback Function called after the request is complete (called when the request is successful or fails ). Parameter: XMLHttpRequest object and a string that describes the successful request type.

    Function (XMLHttpRequest, textStatus) {this; // The options parameter passed when calling this ajax request}

    10. success: Required parameter of the Function type. The callback Function called after the request is successful has two parameters.

    (1) data returned by the server and processed according to the dataType parameter.

    (2) A string describing the status.

    Function (data, textStatus) {// data may be xmlDoc, jsonObj, html, text, etc. this; // The options parameter passed when calling this ajax request}

    11. error:

    A parameter of the Function type is required. The Function called when the request fails. This function has three parameters: XMLHttpRequest object, error message, and captured error object (optional ). Ajax event functions are as follows:

    Function (XMLHttpRequest, textStatus, errorThrown) {// generally, textStatus and errorThrown have only one of them containing information this; // The options parameter passed when calling this ajax request}

    12. contentType:

    It must be a String parameter. When the message is sent to the server, the content encoding type is "application/x-www-form-urlencoded" by default ". This default value is suitable for most applications.

    13. dataFilter:

    A Function that requires a Function type parameter to pre-process the original data returned by Ajax. Provides two parameters: data and type. Data is the original data returned by Ajax, and type is the dataType parameter provided when jQuery. ajax is called. The value returned by the function will be further processed by jQuery.

    Function (data, type) {// return the processed data return data ;}

    14. dataFilter:

    A Function that requires a Function type parameter to pre-process the original data returned by Ajax. Provides two parameters: data and type. Data is the original data returned by Ajax, and type is the dataType parameter provided when jQuery. ajax is called. The value returned by the function will be further processed by jQuery.

    Function (data, type) {// return the processed data return data ;}

    15. global:

    It must be a Boolean parameter. The default value is true. Indicates whether to trigger a global ajax event. Setting false does not trigger global ajax events. ajaxStart or ajaxStop can be used to control various ajax events.

    16. ifModified:

    It must be a Boolean parameter. The default value is false. Obtain New data only when the server data changes. The server data change judgment is based on the Last-Modified header information. The default value is false, indicating that the header information is ignored.

    17. jsonp:

    A parameter of the String type is required. The name of the callback function is rewritten in a jsonp request. This value is used to replace "callback =? "Callback" in the URL parameter of this GET or POST request, for example, {jsonp: 'onjsonpload'} causes "onJsonPLoad =? "To the server.

    18. username:

    A String-type parameter is required. It is the username used to respond to the HTTP access authentication request.

    19. password:

    It must be a String type parameter, used to respond to the password of the HTTP access authentication request.

    20. processData:

    It must be a Boolean parameter. The default value is true. By default, the sent data will be converted to an object (technically not a string) to work with the default content type "application/x-www-form-urlencoded ". If you want to send DOM tree information or other information that does not want to be converted, set it to false.

    21. scriptCharset:

    A parameter of the String type is required. It is used to force charset modification only when dataType is "jsonp" or "script" and type is GET ). Generally, the local and remote content encoding is not used at the same time.

    $.ajax({      type:"GET",      url:"test.json",      data:{username:$("#username").val(),content:$("#content").val()},      dataType: "json",      success: function(data){             $('#resText').empty();                                                                             varhtml = '';             $.each(data,function(commentIndex, comment){             html += comment['username']  + comment['content'];                        });               }   });

    $. AjaxSetup () method

    When using the ajax () method, you sometimes need to call multiple $. ajax () methods. It is very troublesome to set the request details in each method. To simplify this work, you can use the ajaxSetup () function in JQuery to set global ajax default options.

    $.ajaxSetup({      type:”GET”,      url:”jsp/response.jsp”,      dataType:”xml”});

    Then call the ajax () function. The above parameters are used by default.

    AjaxStart (), ajaxStop (), and other global events

    The former is used for preparation when a request starts to be executed, such as the prompt "getting data ......" The latter is triggered when the request ends and is often used in combination with the former. If you change the prompt to "data has been obtained successfully !", Then gradually disappear

    $("#my").ajaxStart(function(){              $(this).show();          }).ajaxStop(function(){            $(this).hide();          }); 


          

    AjaxStart () and ajaxStop () are global functions. In addition, there are four ajax-related global events in JQuery.

    AjaxComplete () executes the function when the AJAX request is complete.

    AjaxError () executes the function when an AJAX request error occurs.

    AjaxSuccess () executes the function when the AJAX request is successful.

    AjaxSend () executes the function at the beginning of an AJAX request

    $ ("# Msg"). ajaxError (function (event, request, settings) {$ (this). append ("
  2. Error Page: "+ settings. url +"
  3. ");});


    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.