Read more about jquery's Ajax functions ($.get (), $.post (), $.ajax (), $.getjson ()) _jquery

Source: Internet
Author: User
Tags getscript html page

One, $.get (Url,[data],[callback])

Description: The URL is the request address, data is the list of requests, callback is a successful callback function, the function accepts two parameters, the first data returned for the server, the second parameter is the state of the server, optional parameters.

In this case, the server returns the data format is actually a string situation, not the JSON data format we want, this reference is just for comparison
$.get ("data.php", $ ("#firstName. Val ()"), function (data) {$ ("#getResponse"). HTML (data); The returned data is a string type);

II, $.post (Url,[data],[callback],[type])

Description: This function is similar to the $.get () parameter, more than a type parameter, type is the requested data type, can be html,xml,json and other types, if we set this parameter to: JSON, then the return format is JSON format, if not set, and $. Get () is returned in the same format as a string of
$.post ("data.php", $ ("#firstName. Val ()"), function (data) {$ ("#postResponse"). HTML (data.name);}, "JSON"//Set the type of Get data , so the resulting data format is of JSON type);

Three, $.ajax (Opiton)

Description: $.ajax () This function is powerful, you can do a lot of precise control of Ajax, you need to specify the relevant information to refer to
$.ajax ({url: "ajax/ajax_selectpictype.aspx", Data:{full: "Fu"},type: "POST", DataType: ' JSON ', success:callback,error : function (er) {backerr (er);}});

IV, $.getjson (Url,[data],[callback])

$.getjson ("data.php", $ ("#firstName. Val ()"), function (Jsondata) {$ ("#getJSONResponse"). HTML (jsondata.id); Without setting, the data type directly obtained is JSON, so it is required to use the Jsondata.id method when calling;

When Ajax meets JQuery based applications are now growing, and for the foreground developer, it is not pleasant to deal directly with the HttpRequest at the bottom. Since jquery encapsulates JavaScript, it must have considered the problem of AJAX applications. Indeed, it would be easier to write Ajax in jquery than it would be to write it directly in JS. (Do not know with jquery long, will lose the knowledge of JS ...) This assumes that you are familiar with the jquery syntax to summarize some of the AJAX applications.

Load Static page

Load (URL, [data], [callback]); URL address of the HTML page requested by the URL (String)
Data (MAP) (optional parameters) sent to the server Key/value
Callback (callback) (optional parameter) callback function when the request completes (does not need to be success)
The load () method can easily load static page content into the specified jquery object. $ (' #ajax-div '). Load (' data.html ');
In this way, the contents of the data.html will be loaded into the DOM object with the ID ajax-div. You can even implement AJAX operations that load portions of content by setting IDs, such as:
$ (' #ajax-div '). Load (' data.html#my-section ');

Implement Get and Post methods

Get (URL, [data], [callback]) URL (String) to send the URL address of the request.

Data (MAP) (optional parameters) to be sent to the server, represented as a Key/value key-value pair, is QueryString appended to the request URL
Callback (callback) (optional parameter) the callback function (which is invoked only if response's return state is success) is loaded on success

Obviously this is a function that implements the Get method, and it's fairly simple to use.

$.get (' login.php ', {id: ' Robin ', Password: ' 123456 ', Gate: ' Index '}, function (data, status) {//data for return object, status for requested State alert (data); Now assume that the server script will return a text "Hello, robin!. , then the browser pops up a dialog box to display the text 
alert (status); The result is success, error, and so on, but here is the function to be able to run when successfully});
Post (URL, [data], [callback], [type]) URL (String) sends the URL address of the request.
Data (MAP) (optional parameter) to be sent to the server, in the form of a Key/value key-value pair,
callback (callback) (optional parameter) is loaded when the callback function succeeds ( The type of the
request data, Xml,text,json, and so on,
is also a simple function that jquery provides, in fact, if the return state of the response is success is the call to the method) type (String) (optional parameter). Post (' regsiter.php ', {id: ' Robin ', Password: ' 123456 ', type: ' User '},function (data, status) {alert (data);}, "JSON");

Event-Driven script load function: Getscript ()

Getscript (URL, [callback]) URL (String) to be loaded into the JS file address

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

The Getscript () function can load JavaScript scripts remotely and execute them. This function can load the JS file across the domain (Magic ...?!). )。 The meaning of this function is huge, it can greatly reduce the amount of code that the page loads initially, because you can load the corresponding JS file according to the user's interaction, instead of loading it all when the page is initialized.

$.getscript (' Ajaxevent.js ', function () {alert ("Scripts loaded!");//Load Ajaxevent.js, and display a dialog box prompt after successful loading. 
});

Building a bridge for data communication: Getjson ()

Getjson (url,[data],[callback]) URL (String) sends the request address

Data (MAP) (optional) Key/value parameters to send

Callback (function) (optional) callback function when successfully loaded.

JSON is an ideal data transmission format that blends well with JavaScript or other host languages and can be used directly by JS. Using JSON to send "naked" data directly via get and post is more logical and more secure. As for the Getjson () function of jquery, just a simplified version of the Ajax () function that sets the JSON parameter.

This function can also be used across domains, compared to get (), post () has some advantages. In addition, this function allows the program to execute the callback function X by writing the request URL in "myurl?callback=x" format.

$.getjson (' feed.php ', {request:images, id:001, Size:large}, function (JSON) {alert (json.images[0].link); 
Here JSON is the remote-returned JSON object, assuming the format is as follows: 
//{' images ': [ 
//{link:images/001.jpg, x:100, y:100}, 
//{link:images/0 02.jpg, x:200, y:} 
//]}; 
);

More low-level Ajax () functions

Although the get () and post () functions are very simple and easy to use, they are not achievable for more complex design requirements, such as making different moves at different times of the Ajax delivery. jquery provides a more specific function: Ajax ().

Ajax (Options) Ajax () provides a large amount of parameters, so you can achieve quite complex functionality.

You can specify XML, script, HTML, JSON as its data type, you can set up processing functions for Beforesend, error, sucess, complete, and many other parameters can be customized to completely define the user's Ajax experience. In the following example, we use Ajax () to invoke an XML document:

$.ajax ({ 
URL: ' doc.xml ', 
type: ' Get ', 
dataType: ' xml ', 
timeout:1000, 
error:function () { 
Alert (' Error loading XML document '); 
}, 
success:function (XML) { 
alert (XML) 
; Here XML is the jquery object of XML, and you can find nodes in it with the methods of finding (), next (), or XPath, and using jquery to manipulate HTML objects without distinction 
}.

Learn more about AJAX events

Some of the methods discussed earlier have their own event-handling mechanisms, which can only be said to be local functions from the page as a whole. jquery provides the definition of AJAX global functions to meet special requirements. Here are all the functions that jquery provides (listed in the order in which they are triggered):

Ajaxstart (global event) begins a new Ajax request, and no other AJAX request is in progress at this time Beforesend (local event) when an AJAX request starts. If necessary, you can set up a global event success (local event) trigger when the XMLHttpRequest Object Ajaxsend (global event) request succeeds. That is, the server does not return an error, the returned data has no errors ajaxsuccess global event Global Request success error (local event) is triggered only if an error occurs.

You can't execute both success and error two callback functions Ajaxerror global event Global error triggering complete (local event) Whether you request success or failure, even if the synchronization request, you can trigger the event when the request completes Ajaxcomplete Trigger Ajaxstop When global event Global request completes (global event) when there is no Ajax in progress, triggering local events is described in previous functions, and we mainly look at global events. Global event monitoring for an object, the global Ajax action, will have an impact on it. For example, when the page is in Ajax operation, the DIV with the id "loading" is displayed:

$ ("#loading"). Ajaxstart (function () {$ (this). Show ();});

Global events can also help you write global errors corresponding and successful accordingly, without requiring separate settings for each AJAX request. It is important to note that the parameters of global events are useful. In addition to Ajaxstart, Ajaxoptions, other events have event, XMLHttpRequest, ajaxoptions three parameters. The first parameter is the event itself, the second is the XHR object, and the third is the Ajax parameter object you pass. Displays the global AJAX situation in an object:

$ ("#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");

Obviously, the third parameter can also help you pass the custom parameters you added to the Ajax event.
In a single AJAX request, you can set the global value to False to make this request independent of the Ajax global event.

$.ajax ({url: "request.php", Global:false, 
//Disable global AJAX events.});

If you want to set parameters for global Ajax, you will use the Ajaxsetup () function.

For example, all AJAX requests are passed to request.php, the global method is disabled, and the Post method is enforced:

$.ajaxsetup ({url: "request.php", Global:false, type: "POST"});

Some way you have to know.

Writing Ajax is certainly inseparable from getting the corresponding value from the page. Here are some simple ways to enumerate:

The Val () Val () function returns the value of the form's build, such as the value of any kind of input.

With the selector operation, you can easily get the values of the option group, the Input box, the button, and so on.

$ ("Input[name= ' info ']:text"). Val ()//Returns the value of the text box with the name Info $ ("Input[name= ' Pass ']:p assword"). Val ()//Returns the value of the password box with the first name
$ ("Input[name= ' Save ']:radio"). Val ()//Returns the value of the single option named Save//The Serialize () Serialize function can help you convert all the values of the Form object to a string sequence.

This is handy if you want to write a request in get format.

Serializearray () is similar to serialize () except that it returns a JSON object.

The above is a small series to introduce the detailed interpretation of jquery ajax functions ($.get (), $.post (), $.ajax (), $.getjson ()), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.