Details about Ajax functions of jquery

Source: Internet
Author: User
Tags getscript
$. Get (), $. Post (), $. Ajax (), $. getjson ()


1, $. Get (URL, [data], [callback])



Note: The URL is the request address, the data is the list of request data, and the callback is the callback function after the request is successful. This function accepts two parameters. The first one is the data returned by the server, the second parameter is the server status, which is an optional parameter.



The format of the data returned by the server is actually the string format, not the JSON data format we want. Here we reference it for comparison.


 




1 $ .get ("data.php", $ ("# firstName.val ()"), function (data) {
2 
3 $ ("# getResponse"). Html (data);} // The returned data is a string type
4
5);


Ii. $. Post (URL, [data], [callback], [type])



Description: This function is similar to $. the get () parameter is similar. A type parameter is added, and the type is the data type of the request, which can be HTML, XML, JSON, and Other types. If we set this parameter to JSON, the returned format is in JSON format. If no value is set, it is equal to $. get () returns the same format as a string.


 




$ .post ("emp.do?p=getAllEmp", {id: deptId, x: Math.random ()}, function (data) {
             var arry = eval ("(" + data + ")"); // quote, quote the json string and program the json type array. You can also add a parameter "json" after the $ .post function to specify the received data Json type
             for (var i = 0; i <arry.length; i ++) {
                 var op = new Option (arry [i] .empName, arry [i] .empId);
                 document.getElementById ("emp"). options.add (op);
             }
         });


3, $. Ajax (opiton)



: $. Ajax () is a powerful function that provides many precise control over Ajax. For details, see relevant materials.


$.post("emp.do?p=getAllEmp",{id:deptId,x:Math.random()},function(arry){
            for(var i=0;i<arry.length;i++){
                var op = new Option(arry[i].empName,arry[i].empId);
                document.getElementById("emp").options.add(op);
            }
        },"json");


4, $. getjson (URL, [data], [callback])


 




$.getJSON("dep.do?p=getAllDep",{x:Math.random()},function(arry){
            for(var i=0;i<arry.length;i++){
                var op = new Option(arry[i].deptName,arry[i].deptId);
                document.getElementById("dep").options.add(op);
            }
        });


When Ajax meets jquery has more and more Ajax-based applications. For front-end developers, it is not a pleasant thing to deal directly with the underlying httprequest. Since jquery encapsulates JavaScript, you must have considered Ajax applications. Indeed, writing Ajax with jquery is n times more convenient than writing with JS directly. (I don't know if I will lose my knowledge of JS after I use jquery ......) Let's assume that you are familiar with jquery syntax to summarize some Ajax applications.
Load Static pages


Load (URL, [data], [callback]);URL (string) URL of the requested HTML page
Data (MAP) (optional parameter) Key/value data sent to the server
Callback (callback) (optional) callback function when the request is completed (success is not required)
The load () method can easily Load Static page content to a specified jquery object.
('{Ajax-div'{.load('data.html ');

In this example, the content of data.html is loaded into the DOM object with the ID Ajax-Div. You can even create an ID to load part of the content, such:

('{Ajax-div'{.load('data.html # My-section ');


Implement get and post Methods


Get (URL, [data], [callback])URL (string) the URL of the request sent.
Data (MAP) (optional parameter) the data to be sent to the server, expressed in key/value pairs, will be appended to the request URL as querystring
Callback (callback) (optional parameter) callback function when the load is successful (this method is called only when the response returns success)
Obviously, this is a function dedicated to implementing the get method, and it is quite simple to use.
$ .get ('login.jsp', {
    id: 'Robin',
    password: '123456',
    gate: 'index'
   }, function (data, status) {
    // data is the returned object, and status is the status of the request
    alert (data);
    // Suppose the server script will return a text "Hello Robin!",
Then the browser will pop up a dialog box to display the text
    alert (status);
    // The result is success, error, etc., but here is a function that can be run only if it succeeds
   });
Post (URL, [data], [callback], [type])URL (string) the URL of the request sent.
Data (MAP) (optional parameter) data to be sent to the server, expressed in key/value pairs
Callback (callback) (optional parameter) callback function when the load is successful (this method is called only when the response returns success)
Type (string) (Optional) Type of request data, XML, text, JSON, etc.
It is also a simple function provided by jquery.
 
$.post('regsiter.jsp', {
   id:'Robin',
   password: '123456',
   type:'user'
  },function(data, status) {
   alert(data);
  }, "json");


Event-Driven Script Loading Function: getscript ()


Getscript (URL, [callback])URL (string) Address of the JS file to be loaded
Callback (function) (optional) callback function after successful Loading
The getscript () function can remotely load and execute JavaScript scripts. This function can load JS files across domains (MAGIC ......?!). This function is of great significance. It can greatly reduce the initial loading of pages. CodeBecause you can load the corresponding JS files based on user interaction, instead of loading all the files during page initialization.
$ .getScript ('ajaxEvent.js', function () {
    alert ("Scripts Loaded!");
    // Load ajaxEvent.js and display a dialog prompt after successful loading.
   });


Build a bridge for data communication: getjson ()


Getjson (URL, [data], [callback])URL (string) Sending request address
Data (MAP) (optional) Key/value parameter to be sent
Callback (function) (optional) callback function when the load is successful.
JSON is an ideal data transmission format. It can be well integrated with JavaScript or other remote languages and can be directly used by Js. JSON is more reasonable and secure in structure than the traditional "naked" data directly sent through get and post. For jquery's getjson () function, it is only a simplified version of AJAX () function with JSON parameters. This function can also be used across domains. It has some advantages over get () and post. In addition, this function can write the request URL as "myurl? Callback = x "format, let ProgramExecute Callback Function x.
$ .getJSON ('feed.jsp', {
    request: images,
    id: 001,
    size: large
    }, function (json) {
     alert (json.images [0] .link);
     // here json is the remotely returned json object, assuming its format is as follows:
     // {'images': [
     // {link: images / 001.jpg, x: 100, y: 100},
     // {link: images / 002.jpg, x: 200, y 200:}
     //]};
    }
  );


Underlying Ajax () Functions
Although get () and post () functions are simple and easy to use, they still cannot be implemented for more complex design requirements, such as making different actions at different time periods of Ajax sending. Jquery provides a more specific function: Ajax ().


Ajax (options)Ajax () provides a large ticket parameter, so it can implement quite complex functions.
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 automatically uses the mime information of the http package.
Responsexml or responsetext is returned and passed as a callback function parameter. Available values:

"XML": the XML document is returned and 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. When calling a function in the form of jsonp,

For example, "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, only one of textstatus and errorthown has the 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,

For example, 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}


You can specify XML, script, HTML, and JSON as data types, and set processing functions for beforesend, error, sucess, complete, and other States, many other parameters can also fully define the user's Ajax experience. In the following example, we use Ajax () to call 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, you can use find (), next () or XPath to find nodes in it
No difference with manipulating HTML objects with jQuery
     }
});


Learn more about Ajax events
Some of the methods discussed earlier have their own event processing mechanisms. In general, they can only be called partial functions on the page. Jquery provides the definition of Ajax global functions to meet special requirements. Below are all functions provided by jquery (arranged in the order of triggering ):


Ajaxstart (Global Event) starts a new Ajax request, and no other Ajax requests are in progress at this time. Beforesend (Partial event) triggered when an Ajax request starts. If needed, you can set the XMLHTTPRequest object here. Ajaxsend (Global Event) global events triggered before the request starts Success (Partial event) triggered when the request is successful. That is, the server does not return errors, and the returned data is not. Ajaxsuccess The global event request is successful. Error (Partial event) is triggered only when an error occurs. You cannot execute both the success and error callback functions at the same time. Ajaxerror Triggered when a global error occurs. Complete (Partial event) Whether your request succeeds or fails, even if it is a synchronous request, you can trigger this event when the request is complete. Ajaxcomplete Triggered when a global event request is complete. Ajaxstop (Global Event) triggered when no Ajax is in progress


Local events are described in previous functions. We mainly look at global events. When a global event is monitored for an object, the global Ajax action will affect it. For example, when a page is performing Ajax operations, the DIV with the ID of "loading" is displayed:


 




$ ("# Loading"). ajaxstart (function () {$ (this). Show ();});


Local events can also help you write global errors and success responses without setting them for each Ajax request. It is worth noting that global event parameters are very useful. In addition to ajaxstart and ajaxoptions, other events have three parameters: event, XMLHttpRequest, and ajaxoptions. The first parameter is the event itself, the second is the xhr object, and the third is the Ajax parameter object you passed. Display 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 to pass custom parameters that you add to the Ajax event. In a single Ajax request, you can set the global value to false to separate the request from the global events of Ajax.


 




$. 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, to pass all Ajax requests to request. php, disable the global method, and force the POST method to pass:


 




$. Ajaxsetup ({URL: "request. php", Global: false, type: "Post "});


Some methods you have to know
To write Ajax, you must obtain the corresponding values from the page. Here are some simple examples:


Val ()The Val () function can return the value of form creation, for example, the value of input of any type. In combination with the selector operation, you can easily obtain the values of the sequence group, input boxes, buttons, and other elements.
$ ("input [name = 'info']: text"). val ();
// Return the value of the text box named info
$ ("input [name = 'pass']: password"). val ();
// Return the value of the password box named pass
$ ("input [name = 'save']: radio"). val ();
// Return the value of the radio option named save
// and so on 
Serialize ()The serialize function can help you convert all values of form objects into string sequences. If you want to write a GET request, this is very convenient.Serializearray ()Similar to serialize (), but it returns a JSON object.


Ajax application reference
(WordPress) Use jquery Ajax message: http://hellobmw.com/archives/ajax-comments-with-jquery-for-wordpress.html
Using jquery to realize Ajax-based data query, sorting and paging functions: http://www.malsup.com/jquery/form/



http://www.cnblogs.com/henryfan/archive/2007/01/27/631954.html
jquery-Ajax brushless newest save example: http://www.phpchina.com/1296/viewspace_12580.html
references
simplified Ajax development with jquery: http://www.ibm.com/developerworks/cn/xml/x-ajaxjquery.html
jquery official restart ention: http://docs.jquery.com/Ajax
jquery Ajax full parsing: http://www.cnblogs.com/QLeelulu/archive/2008/04/21/1163021.html
Ajax event in jquery: http://shawphy.com/2008/08/ajax-event-in-jquery.html


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.