JQuery Ajax examples of various ways to use the detailed

Source: Internet
Author: User
Tags getscript

Jquery.get (URL, [data], [callback]): Asynchronous request using Get method


This is a simple GET request function to replace the complex $.ajax. Callback functions can be invoked when the request succeeds. If you need to perform a function when an error occurs, use $.ajax.

Example
Request test.php Web page, ignore return value:

The code is as follows Copy Code

$.get ("test.php");

Example 1

Request test.php Web page, transfer 2 parameters, ignore return value:

The code is as follows Copy Code

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

Example 2

Displays the test.php return value (HTML or XML, depending on the return value):

The code is as follows Copy Code

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

Example 3
Displays the test.cgi return value (HTML or XML, depending on the return value), and adds a set of request parameters:

The code is as follows Copy Code

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

Example 4

The code is as follows Copy 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 is the option configuration information for the AJAX request, please refer to the following figure
alert (data);
Alert (Textstatus),//Request status: Success,error, and so on.
Of course, the error is not captured here, because the callback function is not run at all when the error
alert (this);
});


jquery.post (URL, [data], [callback], [Type]): Asynchronous request using POST method


Parameters:

URL (String): The URL address where the request is sent.

Data (MAP): (optional) The information to be sent to the server, expressed as a Key/value key-value pair.

Callback (function): (optional) the callback function (which is invoked only if the response return state is success) when loading succeeds.

Type (String): (optional) The official description is: type of data to is 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. Callback functions can be invoked when the request succeeds. If you need to perform a function when an error occurs, use $.ajax. Sample code:

Ajax.aspx:

The code is as follows Copy Code

Response.ContentType = "Application/json";
Response.Write ("{result: '" + request["Name"] + ", Hello! (This message comes from server) '} '); JQuery code:
$.post ("Ajax.aspx", {Action: "Post", Name: "Lulu"},
function (data, textstatus) {
Data can be xmldoc, jsonobj, HTML, text, and so on.
This This AJAX request option configuration information, please refer to Jquery.get ().
alert (Data.result);
}, "JSON");

1. Load (URL, [data], [callback]): Loads the remote HTML file code and inserts it into the DOM.

URL: Refers to the address of the file to be imported.
data: Optional parameters; Because load can not only import static HTML files, but also import dynamic scripts, such as PHP files, so to import a dynamic file, we can put the parameters to pass here.
callback: optional parameter; is another function that is executed after the Load method is invoked and the server responds.


One: How to use Data

1. Load a php file, the PHP file does not contain pass parameters

The code is as follows Copy Code
$ ("#myID"). Load ("test.php");

Import test.php Run results in an element with ID #myid
2. Load a PHP file that contains a pass parameter

The code is as follows Copy Code

$ ("#myID"). Load ("test.php", {"name": "Adam"});

The imported PHP file contains a pass-through parameter, similar to the following: Test.php?name=adam
3. Load a PHP file that contains multiple pass parameters. Note: The parameters are separated by commas

The code is as follows Copy Code

$ ("#myID"). Load ("test.php", {"name": "Adam", "Site": "61dh.com"});

The imported PHP file contains a pass-through parameter, similar to the following: test.php?name=adam&site=61dh.com
4. Load a php file, the php file with an array as the passing parameters

The code is as follows Copy Code

$ ("#myID"). Load ("test.php", {' myinfo[] ', ["Adam", "61dh.com"]});

The imported PHP file contains an array pass parameter.
Note: Using load, these parameters are passed as post, so you cannot use get for parameters in test.php.

II: How to use callback

For example, we can use the callback function when the load method gets the server response and slowly displays the loaded content. The code is as follows:

The code is as follows Copy Code

$ ("#go"). Click (function () {

$ ("#myID"). Load ("welcome.php", {"lname": "Cai", "fname": "Adam", function () {

$ ("#myID"). FadeIn (' slow ');

);

});

Note:

After the URL Riga of the load, you can follow the selector.

For example:

The code is as follows Copy Code

$ ("body"). Load ("test.html #a");

This method makes it easy to dynamically load some HTML files, such as forms.

Sample code:

The code is as follows Copy Code

$ (". Ajax.load"). Load ("1500682.html. Post",
function (ResponseText, textstatus, XMLHttpRequest) {
this;//here. This point is the current DOM object, that is $ (". Ajax.load") [0]
alert (responsetext);//Request returned content
alert (textstatus);//Request Status: Success,error
alert (XMLHttpRequest);//xmlhttprequest Object
});


jquery.getscript (URL, [callback]): Load and execute a JavaScript file with a Get-mode request.

Parameters
URL (String): The JS file address is to be loaded.

Callback (function): (optional) After successfully loading the callback function.

Loads and executes a JavaScript file through an HTTP GET request.

Before the JQuery 1.2 version, Getscript can only invoke the same domain JS file. 1.2, you can invoke JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you add a script by getscript, add the delay function.

Parameters
Url,[callback]string,functionv1.0url: To be loaded into the JS file address.

Callback: callback function after successful loading.

Example
Describe:
Load <a title= "/color" class= "External text" href= "H/color" >jquery the official color animation plugin </a> After successful binding color change animation.

The code is as follows Copy Code

HTML Code:
<button id= "Go" >»Run</button>
<div class= "block" ></div>jquery code:
Jquery.getscript ("/jquery.color.js", function () {
$ ("#go"). Click (function () {
$ (". Block"). Animate ({backgroundcolor: ' Pink '}, 1000)
. Animate ({backgroundcolor: ' Blue '}, 1000);
});
});

Describe:

Load and execute test.js.

JQuery Code:

$.getscript ("Test.js");

Describe:

Load and execute test.js, and then display the information successfully.

JQuery Code:

The code is as follows Copy Code

$.getscript ("Test.js", function () {
Alert ("Script loaded and executed.");
});


jQuery Ajax Events

Ajax can trigger many events.
There are two kinds of events, one is a local event, the other is a global event:

Local events: called and assigned by $.ajax.

The code is as follows Copy Code

$.ajax ({
Beforesend:function () {
Handle the Beforesend Event
},
Complete:function () {
Handle the Complete event
}
// ...
});

Global events, which can be bound with bind and unbind to unbind. This is similar to Click/mousedown/keyup and other events. But he can pass it on to every DOM element.

The code is as follows Copy Code

$ ("#loading"). Bind ("Ajaxsend", function () {///Use Bind
$ (this). Show ();
}). Ajaxcomplete (function () {//Direct use Ajaxcomplete
$ (this). Hide ();
});


Of course, one of your AJAX requests does not want to produce global events, you can set the Global:false

  code is as follows copy code

$.ajax ({
   URL: "test.html",
   global:false,
  //...
 });

The sequence of events is as follows:
Ajaxstart Global Events
Start a new Ajax request, and no other AJAX requests are in progress at this time.
Beforesend Local Events
Triggered when an AJAX request starts. If you want, you can set the Xhr object here.
Ajaxsend Global Events
Global events that are triggered before the request starts
Success Local Events
triggered when a request succeeds. That is, the server does not return an error, and the returned data is correct.
Ajaxsuccess Global Events
The global request succeeded
Error local Event
triggered only if an error occurs. You cannot perform both success and error two callback functions at the same time.
Ajaxerror Global Events
Triggered when an error occurs globally
Complete Local Events
Whether you request success or failure, even if the synchronization request, you can trigger the event when the request completes.
Ajaxcomplete Global Events
triggered when a global request completes
Ajaxstop Global Events
Triggered when no Ajax is in progress.

The parameters of the local event callback are clearly written in the document and are not described here.

In global events, except for Ajaxstart and Ajaxstop, all other events have 3 parameters
Event, XMLHttpRequest, Ajaxoptions
The first is the event, the second is the XHR object, and the third parameter is the most useful, and is the parameter of the time when this Ajax was invoked.
For Ajaxerror, there is a fourth parameter thrownerror that is passed only when an exception occurs.
We can use Ajaxoptions to write a global Ajax event.
Like what

The code is as follows Copy Code

$ ("#msg"). Beforesend (function (e,xhr,o) {
$ (this). HTML ("requesting" +o.url);
}). ajaxsuccess (function (e,xhr,o) {
$ (this). HTML (o.url+ "request succeeded");
}). ajaxerror (function (e,xhr,o) {
$ (this). HTML (o.url+ "request Failed");
});

For this example,
This allows us to display the current Ajax state in a very convenient and global way.
Of course, the third argument is actually a parameter passed to Ajax. Get/post/load/getscript/getjson methods are essentially calls to Ajax methods, so the Ajaxoptions.url attribute is always valid.

There are even richer examples.
If you call with Ajax, you can also pass a custom parameter. The following example I have customized a msg parameter to the AJAX call

  code is as follows copy code

//Custom Parameters MSG
$.ajax ({url: "test1.html", type: "Get", msg: "Page One"});
$.ajax ({url: "test2.html", type: "Get", msg: "Page Two"});
$.ajax ({url: "test3.html", type: "Get", msg: "Page Three"});
$.ajax ({url: "test4.html", type: "Get", msg: "Page Four"});
 
//Here you can get the custom parameter Msg.
//This can be used to differentiate between different AJAX requests.
$ ("#msg"). Beforesend (function (e,xhr,o) {
    $ (this). HTML ("requesting +o.msg";
}). Ajaxsuccess (function (e,xhr,o) {
    $ (this). HTML (o.msg+ "request succeeded";
). Ajaxerror (function (e,xhr,o) {
    $ (this). HTML (o.msg+ request failed);
};

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.