Jquery. Ajax usage

Source: Internet
Author: User
Tags getscript
Jquery. Ajax (options)

Parameters:

  • Options

Return Value:

  • XMLHttpRequest

Use http to request a page.

This is jquery's low-level Ajax implementation. For more information about advanced abstraction, see $. Set and $. Post. These methods are easier to understand and use. However, there are functional limitations (for example, there are no error handler functions ).

Warning if the data type is specified as "script", the POST method is automatically converted to the get method. (Because the script will be loaded as a script label embedded in the page)

The $. Ajax () function returns the XMLHTTPRequest object it creates. In most cases, you do not need to operate this object directly. Generally, the XMLHTTPRequest object is used when you need to manually interrupt the XMLHttpRequest request.

Note: If you specify the data types listed below, make sure that the server sends the correct mime response type (for example, the. XML type is "text/XML "). Incorrect MIME types can cause unexpected errors in the script. See the Ajax example to learn more about the data type.

$. Ajax () functions require a parameter, an object containing a key/value pair, which is used to initialize and operate the request object.

In jquery 1.2, If you specify a jsonp callback function, you can load JSON data from other domains, similar to "myurl? Callback =? ". Jquery will automatically call the correct method name to replace the query string and execute the callback function you specified. Alternatively, you can specify the Data Type callback function of jsonp, which is automatically added to the Ajax request.

Parameter options:

Async (true) Data Type: Boolean
By default, all requests are sent asynchronously (true by default ). To send a synchronization request, set the value to false. Note: Synchronous requests may temporarily lock the browser and cannot perform any operations when the request is activated.
Beforesend data type: Function
A preprocessing function is used to modify the XMLHTTPRequest object and set a custom header before sending. XMLHttpRequest is passed as a unique parameter. This is an Ajax event.

function (XMLHttpRequest) {  this; // the options for this ajax request}
Cache (true) Data Type: Boolean
The newly added parameter in jquery 1.2. If it is set to false, the browser is forced not to cache the requested page.
Complete data type: Function
The function that is executed when the request is completed (after successful or failed ). This function has two parameters: the XMLHTTPRequest object and a status string describing HTTP. This is an Ajax event.

function (XMLHttpRequest, textStatus) {  this; // the options for this ajax request}
Contenttype ("application/X-WWW-form-urlencoded") Data Type: String
The content type of the data sent to the server. The default value is "application/X-WWW-form-urlencoded", which is suitable for most cases.
Data data type: object, string
The data to be sent to the server. If it is not a string, it is converted into a query string. In the GET request, it is added to the end of the URL. To prevent this automatic conversion, check the processdata option. The data object must be a set of key/value pairs. If the value corresponding to a key is an array, jquery assigns the value to the same key attribute. For example, {FOO: ["bar1", "bar2"]} is changed to '& Foo = bar1 & Foo = bar2 '.
Datatype (Intelligent guess (XML or HTML) Data Type: String
Type of the returned value from the server. If it is not explicitly specified, jquery will automatically pass responsexml or responsetext to the callback function specified by success based on the actual returned MIME type. Valid types (the returned type result value will be passed to the callback function specified by success as the first parameter) include:

  • "XML": returns an XML document that can be processed by jquery.
  • "Html": HTML code in text format. Including the script tag after the evaluation.
  • "Script": evaluate the response as a javascript statement and return plain text. This script is not cached unless the cache option is set. If it is set to the script type, the POST method is converted to the get method.
  • "JSON": evaluate the response as JSON and return a JavaScript Object.
  • "Jsonp": Use jsonp to load a JSON code block. It will be added at the end of the URL "? Callback =? "To specify the callback function. (Supported by jquery 1.2 or later)
  • "Text": String in text format
      Error Data Type: Function
      The function executed when the request fails. A function has three parameters: XMLHTTPRequest object, an error type generated by a description, and an optional exception object. This is an Ajax event.

      function (XMLHttpRequest, textStatus, errorThrown) {  // typically only one of textStatus or errorThrown   // will have info  this; // the options for this ajax request}
      Global (true) Data Type: Boolean
      Whether to trigger a global Ajax event handler for the current request. The default value is true. Setting false can prevent triggering global event processing functions such as ajaxstart and ajaxstop. This can be used to control multiple different Ajax events.
      Ifmodified (false) Data Type: Boolean
      The request is successful only when the response has been modified since the previous request. It is implemented by checking the value of last-modified in the header. The default value is false, indicating that the header check is ignored.
      Jsonp data type: String
      In the jsonp request, reset the callback function. This value is used to replace 'callback =? . 'Callback =? 'Is located at the end of the URL in the GET request or the data transmitted by the POST request. Therefore, if {jsonp: 'onjsonpload'} is set, 'onjsonpload =? 'Send to the server.
      Processdata (true) Data Type: Boolean
      By default, if the data option is passed into an object rather than a string, it will be automatically processed and converted into a query string, to adapt to the default Content-Type -- "application/X-WWW-form-urlencoded ". To send domdocuments, set this option to false.
      Success data type: Function
      The function called when the request is successful. This function will obtain two parameters: the data returned from the server (formatted according to datatype) and a status string describing the HTTP. This is an Ajax event.

      function (data, textStatus) {  // data could be xmlDoc, jsonObj, html, text, etc...  this; // the options for this ajax request}
      Timeout data type: Number
      If a global timeout is set through $. ajaxsetup, this function uses a local timeout to overwrite the global timeout (in milliseconds ). For example, you can set a long latency to a special request, while all other requests use a delay of 1 second. For more information about global latency, see $. ajaxtimeout ().
      Type ("get") Data Type: String
      The request type ("Post" or "get"). The default value is "get ". Note: Other HTTP request methods, such as put and delete, can also be used here. They were not supported by all browsers at that time.
      URL (the current page) Data Type: String
      Target URL of the request
      Username data type: String
      Username can be used to respond to an HTTP connection request.

Instance

Load and execute a Javascript file.

$.ajax({  type: "GET",  url: "test.js",  dataType: "script"});

Save the data to the server and notify the user.

$.ajax({   type: "POST",   url: "some.php",   data: "name=John&location=Boston",   success: function(msg){     alert( "Data Saved: " + msg );   } });

Obtain the latest version of an HTML page.

$.ajax({  url: "test.html",  cache: false,  success: function(html){    $("#results").append(html);  }});

Load data synchronously. The browser is blocked when the request is executed. This is a better way to ensure data synchronization is more important than interaction.

var html = $.ajax({  url: "some.php",  async: false }).responseText;

Send XML document data to the server. The automatic conversion of data to string is disabled by setting processdata to false.

var xmlDocument = [create xml document]; $.ajax({   url: "page.php",   processData: false,   data: xmlDocument,   success: handleResponse });
Load (URL, [data], [callback])

Parameters:

  • URL (string): the URL address of the loaded page.
  • Params (MAP): (optional) Key/value pair parameter sent to the server.
  • Callback (function): (optional) function executed when data loading is complete.
    function (responseText, textStatus, XMLHttpRequest) {  this; // dom element}

Return Value:

  • Jquery

Load a remote HTML content to a DOM node. By default, the get method is used to send requests. If additional parameters are specified, the POST method is used to send requests. In jquery 1.2, you can specify a jquery selector in the URL parameter. This filters the returned HTML document and obtains only the elements matching the selector in the document. This syntax is similar to "url # Some> selector ".

Instance

Load the sidebar navigation part of the document to an unordered list.

$("#links").load("/Main_Page #p-Getting-Started li");

Load the feeds.html file into the DIV with the ID of feeds.

$("#feeds").load("feeds.html");

Same as above, but an additional parameter is sent and a user-defined function is executed after the response is complete.

$("#feeds").load("feeds.php", {limit: 25}, function(){   alert("The last 25 entries in the feed have been loaded"); });
Jquery. Get (URL, [data], [callback])

Parameters:

  • URL (string): URL address of the loaded page
  • Map (optional): (optional) Key/value pair parameter sent to the server
  • Callback (function): (optional) function executed when the remote page is loaded
    Function (data, textstatus) {// data can be xmldoc, jsonobj, HTML, text, etc. .. This; // The options for this Ajax request}

Return Value:

  • XMLHttpRequest

Use get to request a page.

This is a simple way to send a GET request to the server. It can specify a callback function that is executed after the request is complete (only when the request is successful ). If you also need to set the error and success callback functions, you need to use $. Ajax.

Instance

Request the test. PHP page and ignore the returned value.

$.get("test.php");

Request the test. PHP page and send additional data (ignore returned values ).

$.get("test.php", { name: "John", time: "2pm" } );

Display the returned values from the test. php request (HTML or XML, based on different return values ).

$.get("test.php", function(data){  alert("Data Loaded: " + data);});

The returned value of the additional data request sent to test. cgi (HTML or XML, based on different return values) is displayed ).

$.get("test.cgi", { name: "John", time: "2pm" },  function(data){    alert("Data Loaded: " + data);  });
Jquery. getjson (URL, [data], [callback])

Parameters:

  • URL (string): URL address of the loaded page
  • Map (optional): (optional) Key/value pair parameter sent to the server
  • Callback (function): (optional) function executed when data loading is complete
    function (data, textStatus) {  // data will be a jsonObj  this; // the options for this ajax request}

Return Value:

  • XMLHttpRequest

Use get to request JSON data.

In jquery 1.2, If you specify a jsonp callback function, you can load JSON data from other domains, similar to "myurl? Callback =? ". Jquery will automatically call the correct method name to replace the query string and execute the callback function you specified. Alternatively, you can specify the Data Type callback function of jsonp, which is automatically added to the Ajax request. Note: Remember, that lines after this function will be executed before callback.

Instance

Load the latest four pictures of cats from the Flickr jsonp API

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",        function(data){          $.each(data.items, function(i,item){            $("

Load JSON data from test. js and read the name value from the returned JSON data.

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

Load JSON data from test. JS, pass an additional parameter, and read the name value from the returned JSON data.

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

Display the return value of the request sent to test. php (HTML or XML, based on different return values ).

$.getIfModified("test.php", function(data){  alert("Data Loaded: " + data);});

The returned value of the request sent to test. php (HTML or XML, based on different return values) is displayed, and an additional parameter is provided.

$.getIfModified("test.php", { name: "John", time: "2pm" },  function(data){    alert("Data Loaded: " + data);  });

Lists the query results returned from pages. php and converts the returned array to an HTML code.

var id=$("#id").attr("value");  $.getJSON("pages.php",{id:id},dates);function dates(datos){  $("#list").html("Name:"+datos[1].name+"<br>"+"Last Name:"+datos[1].lastname+"<br>"+"Address:"+datos[1].address);}
Jquery. getscript (URL, [callback])

Parameters:

  • URL (string): URL address of the loaded page
  • Callback (function): (optional) function executed when data loading is complete
    Function (data, textstatus) {// data should be JavaScript this; // The options for this Ajax request}

Return Value:

  • XMLHttpRequest

Use get to request and execute JavaScript files.

Before jquery 1.2, getscript can only load scripts from the host where the page is located. In 1.2, you can load scripts from any host. Warning Safari 2 and earlier versions cannot correctly recognize scripts in global context. If you load a function using getscript, ensure that you set a delay to execute this script.

Instance

We dynamically load a new official jquery color animation plug-in. After loading, we bind some animation effects to the elements.

$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){  $("#go").click(function(){    $(".block").animate( { backgroundColor: 'pink' }, 1000)      .animate( { backgroundColor: 'blue' }, 1000);  });});

Load and execute the test. js Javascript file.

$.getScript("test.js");

Load and execute the test. js Javascript file. A warning message is displayed after the execution is completed.

$.getScript("test.js", function(){  alert("Script loaded and executed.");});
Jquery. Post (URL, [data], [callback], [type])

Parameters:

  • URL (string): URL address of the loaded page
  • Map (optional): (optional) Key/value pair parameter sent to the server
  • Callback (function): (optional) function executed when data loading is complete
    Function (data, textstatus) {// data may be xmldoc, jsonobj, HTML, text, etc. .. This; // The options for this Ajax request}
  • String
    $.postJSON = function(url, data, callback) { $.post(url, data, callback, "json");};

Return Value:

  • XMLHttpRequest

Use post to request a page.

This is a simple method to send a POST request to the server. It can specify a callback function that is executed after the request is complete (only when the request is successful ). If you also need to set the error and success callback functions, you need to use $. Ajax.

Ajaxcomplete (callback)

Parameters:

  • Callback (function): the function to be executed

    function (event, XMLHttpRequest, ajaxOptions) {  this; // dom element listening}

Return Value:

  • Jquery

When an Ajax request ends, a function is executed. This is an Ajax event

Instance

A message is displayed when the Ajax request is complete.

$("#msg").ajaxComplete(function(request, settings){   $(this).append("<li>Request Complete.</li>"); });
Ajaxerror (callback)

Parameters:

  • Callback (function): the function to be executed

    function (event, XMLHttpRequest, ajaxOptions, thrownError) {  // thrownError only passed if an error was caught  this; // dom element listening}

Return Value:

  • Jquery

When an Ajax request fails, execute a function. This is an Ajax event.

Instance

An error message is displayed when an Ajax request is incorrect.

$("#msg").ajaxError(function(request, settings){   $(this).append("<li>Error requesting page " + settings.url + "</li>"); });
Ajaxsend (callback)

Parameters:

  • Callback (function): the function to be executed

    function (event, XMLHttpRequest, ajaxOptions) {  this; // dom element listening}

Return Value:

  • Jquery

Execute a function when an Ajax request is sent. This is an Ajax event.

Instance

When an Ajax request is sent, a message is displayed.

$("#msg").ajaxSend(function(evt, request, settings){   $(this).append("<li<Starting request at " + settings.url + "</li<"); });
Ajaxstart (callback)

Parameters:

  • Callback (function): the function to be executed

    function () {  this; // dom element listening}

Return Value:

  • Jquery

Execute a function when an Ajax request starts but is not activated. This is an Ajax event.

Instance

The loading information is displayed when the Ajax request starts (and is not activated.

$("#loading").ajaxStart(function(){   $(this).show(); });
Ajaxstop (callback)

Parameters:

  • Callback (function): the function to be executed

    function () {  this; // dom element listening}

Return Value:

  • Jquery

When all Ajax operations are stopped, execute a function. This is an Ajax event.

Instance

When all Ajax requests are stopped, the loading information is hidden.

$("#loading").ajaxStop(function(){   $(this).hide(); });
Ajaxsuccess (callback)

Parameters:

  • Callback (function): the function to be executed

    function (event, XMLHttpRequest, ajaxOptions) {  this; // dom element listening}

Return Value:

  • Jquery

When an Ajax request is successfully completed, execute a function. This is an Ajax event

Instance

When the Ajax request is successfully completed, the information is displayed.

$("#msg").ajaxSuccess(function(evt, request, settings){   $(this).append("<li>Successful Request!</li>"); });
Jquery. ajaxsetup (options)

Parameters:

  • Options: Key/value pairs used for Ajax requests

Set global settings for all Ajax requests. View the $. Ajax function to obtain all the options.

Instance

Set the default global Ajax request option.

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

Return Value:

  • Jquery

Concatenates a group of input elements by name and value. The returned value is similar to single = single2 & multiple = multiple & multiple = multiple3 & Radio = Radio2. In jquery 1.2. The serialize method implements the correct sequence of form elements without the support of plug-ins.

Instance

A query string that connects to form elements and can be used to send Ajax requests.

function showValues() {      var str = $("form").serialize();      $("#results").text(str);    }    $(":checkbox, :radio").click(showValues);    $("select").change(showValues);    showValues();
Serializearray ()

Return Value:

  • Jquery

Concatenates all form and form elements (similar to the. serialize () method), but returns a JSON data format.

Instance

Obtain a set of values from the form and display them.

function showValues() {      var fields = $(":input").serializeArray();      alert(fields);      $("#results").empty();      jQuery.each(fields, function(i, field){        $("#results").append(field.value + " ");      });    }    $(":checkbox, :radio").click(showValues);    $("select").change(showValues);    showValues();
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.