Jquery Ajax example

Source: Internet
Author: User
Tags getscript
Document directory
  • Syntax
  • Syntax
  • Syntax
  • Syntax

 

Jquery Ajax example

 

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.

Definition and usage

The load () method loads data from the server through Ajax requests and places the returned data in the specified element.

Note: there is also
Load jquery
Event method. Which one to call depends on the parameter.

Syntax
load(url,data,function(response,status,xhr))

Parameters Description
URL Specifies the URL to which the request is sent.
Data Optional. Specifies the data sent to the server together with the request.
Function (response, status, xhr)

Optional. Specifies the function that runs when the request is complete.

Additional parameters:

  • Response-Contains the result data from the request
  • Status-Request status ("success", "notmodified", "error", "timeout", or "parsererror ")
  • Xhr-Contains the XMLHTTPRequest object.

 

Use an Ajax request to change the text of the DIV element:

$("button").click(function(){  $("div").load('demo_ajax_load.txt');});

 

 

Load page fragments

The. Load () method, unlike $. Get (), allows us to specify a part of the remote document to be inserted. This is implemented through the special Syntax of URL parameters. If the string contains one or more spaces, the string followed by the first space is the jquery selector that determines the loaded content.

We can modify the example above so that we can use a part of the obtained document:

$("#result").load("ajax/test.html #container");

If you execute this method, the content of Ajax/test.html will be retrieved. However, jquery will then parse the returned document to find the elements with the container ID. This element, along with its content, will be inserted into the element with the result ID, and the rest of the retrieved documents will be discarded.

Jquery uses the browser's. innerhtml attribute to parse the retrieved document and insert it into the current document. In this process, the browser often filters out elements from the document, such as <HTML>, <title>, or

Note: Due to browser security restrictions, most "ajax" requests comply with the same-origin policy. Requests cannot retrieve data from different domains, subdomains, or protocols.

 

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.

Definition and usage

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

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.

Syntax
$(selector).get(url,data,success(response,status,xhr),dataType)

Parameters Description
URL Required. Specifies the URL of the request.
Data Optional. Specifies the data sent to the server together with the request.
Success (response, status, xhr)

Optional. Specifies the function that runs when the request is successful.

Additional parameters:

  • Response-contains the result data from the request
  • Status-contains the Request status
  • Xhr-contains XMLHTTPRequest object
Datatype

Optional. Specifies the expected server response data type.

By default, jquery performs intelligent judgment.

Possible types:

  • "XML"
  • "Html"
  • "Text"
  • "Script"
  • "JSON"
  • "Jsonp"

 

Use the Ajax GET request to change the text of the DIV element:

$("button").click(function(){  $.get("demo_ajax_load.txt", function(result){    $("div").html(result);  });});

 

Display the return value of test. cgi (HTML or XML, depending on the returned value), add a set of request parameters:

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

 

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.

Definition and usage

The post () method loads data from the server through an http post request.

Syntax
jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)

Parameters Description
URL Required. Specifies the URL to which the request is sent.
Data Optional. Ing or string value. Specifies the data sent to the server together with the request.
Success (data, textstatus, jqxhr) Optional. The callback function executed when the request is successful.
Datatype

Optional. Specifies the expected server response data type.

Intelligent judgment (XML, JSON, script, or HTML) is performed by default ).

 

Obtain the content of the test. PHP page, store it as an xmlhttpresponse object, and process it using the JavaScript function process:

$.post("test.php", { name: "John", time: "2pm" },   function(data){     process(data);   }, "xml");

 

Obtain the JSON format content returned by the test. PHP page:

$.post("test.php", { "func": "getNameAndTime" },   function(data){     alert(data.name); // John     console.log(data.time); //  2pm   }, "json");

 

 

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.

Definition and usage

The getscript () method loads and executes Javascript files through http get requests.

Syntax
jQuery.getScript(url,success(response,status))

Parameters Description
URL The URL string to be requested.
Success (response, status)

Optional. Specifies the callback function executed after the request is successful.

Additional parameters:

  • Response-Contains the result data from the request
  • Status-Request status ("success", "notmodified", "error", "timeout", or "parsererror ")

 

Load and execute test. js. After successful execution, the information is displayed:

$.getScript("test.js", function(){  alert("Script loaded and executed.");});

 

 

 

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 and set the data type
Jsonp. 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. 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.

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, textstatus and errorthown have only one 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 cocould 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

}

});

 

·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>

 

 

 

 

 

 

For more information, see:

Http://www.w3school.com.cn/jquery/jquery_ref_ajax.asp

 

 

 

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.