One, $.get (Url,[data],[callback])
Description: URL is the request address, data is the list of request data, callback is the callback function after the successful request, the function accepts two parameters, the first is the data returned by the server, the second parameter is the state of the server, is an optional parameter. In this case, the format of the server return data is actually a string situation, not the JSON data format we want, in this reference just to compare the description
The code is as follows:
$.get ("data.php", $ ("#firstName. Val ()"), function (data) {
$ ("#getResponse"). HTML (data);
The data returned by}//is a string type
);
ii. $.post (Url,[data],[callback],[type])
Description: This function is similar to the $.get () parameter, has a type parameter, type is the requested data type, can be a type of Html,xml,json, if we set this parameter to: JSON, then the returned format is in JSON format, if not set, and $. Get () returns the same format as the string.
The code is as follows: $.post ("data.php", $ ("#firstName. Val ()"), function (data) {
$ ("#postResponse"). HTML (data.name);
}, "JSON"//sets the type of get data, so the resulting data format is JSON-type
);
san, $.ajax (Opiton)
Description: $.ajax () This function is powerful, you can do a lot of precise control of Ajax, please refer to the relevant information for detailed description
The code is as follows: $.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])
The code is as follows: $.getjson ("data.php", $ ("#firstName. Val ()"), function (Jsondata) {
$ ("#getJSONResponse"). HTML (jsondata.id);} There is no need to set up, the data type directly obtained is JSON, so we need to use Jsondata.id method when calling
);
When Ajax meets JQuery Ajax-based applications are now more and more, and for front-desk developers, it is not a pleasant thing to deal directly with the underlying HttpRequest. Since jquery encapsulates JavaScript, it must have considered the problem of AJAX applications. Indeed, if using jquery to write Ajax would be more convenient than the direct use of JS write n times. (Do not know the long with jquery, will not lose the knowledge of JS ...) This assumes that you are already familiar with the jquery syntax to summarize some of the applications of Ajax.
Loading static pages
Load (URL, [data], [callback]);
URL address of the URL (String) of the requested HTML page
Data (MAP) (optional parameters) sent to the server Key/value
Callback (callback) (optional parameter) callback function when the request is complete (does not need to be success)
The load () method can easily load static page content into a specified jquery object.
The code is as follows: $ (' #ajax-div '). Load (' data.html ');
In this way, the contents of the data.html will be loaded into the DOM object with ID ajax-div. You can even implement an AJAX operation that loads some content by making an ID, such as:
The code is as follows: $ (' #ajax-div '). Load (' data.html#my-section ');
Implementing the Get and Post methods
Get (URL, [data], [callback])
URL (String) to send the requested URL address.
Data (MAP) (optional parameter) to be sent to the server, expressed as a Key/value key-value pair, is appended to the request URL as QueryString
Callback (callback) (optional parameter) The callback function when loading succeeds (only if the return state of response is success the method is called)
Obviously this is a function that implements get mode, which is quite simple to use.
The code is as follows: $.get (' login.php ', {
ID: ' Robin ',
Password: ' 123456 ',
Gate: ' Index '
}, function (data, status) {
Data is the returned object, status is the requested State
alert (data);
At this point, assume that the server script returns a text "Hello, robin! ", then the browser will pop up a dialog box to display the paragraph text
alert (status);
The result is success, error, and so on, but this is a function that will run when it succeeds.
});
Post (URL, [data], [callback], [type])
URL (String) to send the requested URL address.
Data (MAP) (optional parameter) to be sent to the server, expressed as a Key/value key-value pair
Callback (callback) (optional parameter) The callback function when loading succeeds (only if the return state of response is success the method is called)
Type (String) (optional parameter) request data types, Xml,text,json, etc.
is also a handy function of jquery, in fact the usage
The code is as follows: $.post (' regsiter.php ', {
ID: ' Robin ',
Password: ' 123456 ',
Type: ' User '
},function (data, status) {
alert (data);
}, "JSON");
Event-Driven script loader function: GetScript ()
GetScript (URL, [callback])
URL (String) to be loaded into the JS file address
Callback (function) (optional) After successful load callback function
The GetScript () function can be loaded remotely into JavaScript scripts and executed. This function can be loaded into JS files across domains (magical ...!!). )。 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, without having to load it all when the page is initialized.
The code is as follows: $.getscript (' Ajaxevent.js ', function () {
Alert ("Scripts loaded!");
Loads the Ajaxevent.js and displays a dialog prompt after a successful load.
});
Building a bridge for data communication: Getjson ()
Getjson (Url,[data],[callback])
URL (String) to send the request address
Data (MAP) (optional) Key/value parameters to be sent
Callback (function) (optional) The callback function when loading succeeds.
JSON is an ideal data transmission format, it can be well fused with JavaScript or other host language, and can be used directly by JS. Using JSON to send "naked" data directly through GET, post, is structurally more reasonable and more secure. As for jquery's Getjson () function, it's just a simplified version of the Ajax () function that sets the JSON parameter. This function can also be used across domains, with a certain advantage over get () and post (). In addition, this function can be used to write the request URL as a "myurl?callback=x" format, so that the program executes the callback function X.
The code is as follows: $.getjson (' feed.php ', {
Request:images,
ID:001,
Size:large
}, function (JSON) {
alert (Json.images[0].link);
Here JSON is the JSON object that is sent back remotely, assuming the following format:
{' Images ': [
{link:images/001.jpg, x:100, y:100},
{link:images/002.jpg, x:200, y 200:}
//]};
}
);
the lower-level Ajax () function, although the get () and post () functions are simple and easy to use, are not achievable for more complex design requirements, such as making different actions at different times of the Ajax send. jquery provides a more specific function: Ajax ().
Ajax (Options)
Ajax () provides a large amount of parameters, so you can implement quite complex functions.
Name of parameter |
Type |
Describe |
Url |
String |
(Default: Current page address) sends the requested address. |
Type |
String |
(Default: "Get") The Request method ("POST" or "get"), the default is "get". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it. |
Timeout |
Number |
Sets the request time-out (in milliseconds). This setting overrides the global settings. |
Async |
Boolean |
(default: TRUE) by default, all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the sync request will lock the browser, and the user's other actions must wait for the request to complete before it can be executed. |
Beforesend |
Function |
You can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header.
The XMLHttpRequest object is the only parameter. function (XMLHttpRequest) {this;//the "options for this" Ajax request} function (XMLHttpRequest) {this;//the options For this AJAX request}
|
Cache |
Boolean |
(default: TRUE) JQuery 1.2 new feature, set to False will not load the request information from the browser cache. |
Complete |
Function |
The callback function after the request completes (called when the request succeeds or fails).
Parameters: XMLHttpRequest Object, Success information string. function (XMLHttpRequest, textstatus) {this;//the options for this Ajax request} function (XMLHttpRequest, textstatus) {This;//the options for this AJAX request} |
ContentType |
String |
(Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. The default values are suitable for most applications. |
Data |
Object, String |
Data sent to the server. is automatically converted to the request string format. The GET request will be appended to the URL. View the ProcessData option description to disallow this automatic conversion. Must be a key/value format. If an array, JQuery automatically corresponds to the same name for the different values. such as {foo:["bar1", "Bar2"]} is converted to ' &foo=bar1&foo=bar2′. |
DataType |
String |
Expected data type returned by the server. If not specified, JQuery will automatically be based on the HTTP packet MIME information Returns Responsexml or ResponseText, and is passed as a callback function parameter, with the available values:"XML": Returns an XML document that can be processed with jQuery. HTML: Returns plain text HTML information, including the script element. "Script": Returns plain text JavaScript code. Results are not automatically cached. "JSON": Returns the JSON data. "JSONP": Jsonp format. When a function is called using the JSONP form, Like "myurl?callback=?" JQuery will be replaced automatically? is the correct function name to execute the callback function. |
Error |
Function |
(Default: This method is called when a request for automatic judgment (XML or HTML) fails.) This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being captured. function (XMLHttpRequest, textstatus, Errorthrown) {//normally textstatus and Errorthown only one of which has the value of this; Jax Request} function (XMLHttpRequest, textstatus, Errorthrown) {//normally textstatus and Errorthown only one has the value of this;//the Opti ONS for this AJAX request} |
Global |
Boolean |
(default: TRUE) whether to trigger global AJAX events. Setting to False will not trigger a global AJAX event. such as Ajaxstart or Ajaxstop. Can be used to control different AJAX events |
Ifmodified |
Boolean |
(default: false) to get new data only when the server data changes. Use the HTTP packet last-modified header information to determine. |
ProcessData |
Boolean |
(default: TRUE) by default, the sent data is converted to an object (technically not a string) To match the default content type "application/x-www-form-urlencoded". Set to False if you want to send DOM tree information or other information that you do not want to convert. |
Success |
Function |
The callback function after the request succeeds. This method has two parameters: the server returns data, returns the status function (data, textstatus) {//data could be xmldoc, jsonobj, HTML, text, etc ... this;//the options for this Ajax requ EST} function (data, textstatus) {//data could be xmldoc, jsonobj, HTML, text, etc ... this;//the options for this AJA X Request} |
You can specify XML, script, HTML, JSON as its data type, you can set the processing function for Beforesend, error, sucess, complete and other states, and many other parameters can also be customized to completely define the user's Ajax experience. In the following example, we use Ajax () to invoke an XML document:
The code is as follows: $.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, and other methods to find the node, and the use of jquery to manipulate the HTML object is no different
}
});
Learn more about AJAX events
Some of the methods discussed earlier have their own event handling mechanism, which can only be described as local functions from the overall page. jquery provides the definition of an AJAX global function to meet specific requirements. The following are all the functions provided by jquery (in the order of the triggering sequence below):
Ajaxstart
(global event) starts a new AJAX request, and no other AJAX request is in progress at this time
Beforesend
(local event) is triggered when an AJAX request starts. If necessary, you can set the XMLHttpRequest object here
Ajaxsend
Global event triggered before the request starts (global event)
Success
triggered when the request is successful (local event). That is, the server does not return an error and the returned data is not error
Ajaxsuccess
Global Event Global Request succeeded
Error
(local event) is triggered only when an error occurs. You cannot perform both success and error two callback functions at the same time
Ajaxerror
Global event triggered when an error occurs globally
Complete
(local event) Whether you request success or failure, even if the request is synchronous, you can trigger the event when the request is complete
Ajaxcomplete
triggered when global event global request completes
Ajaxstop
(global event) triggered when no Ajax is in progress
Local events are described in previous functions, and we look at global events in the main. A global event listener for an object will have an impact on the global Ajax action. For example, when the page is doing an AJAX operation, the DIV with the id "loading" is displayed:
The code is as follows: $ ("#loading"). Ajaxstart (function () {
$ (this). Show ();
});
Global events can also help you write global errors appropriately and successfully accordingly, without having to set up independently for each AJAX request. It is necessary to point out that the parameters of the global event 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 that you passed. Displays the global AJAX situation in an object:
The code is as follows: $ ("#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 value of global to false to make this request independent of the Ajax global event.
The code is as follows: $.ajax ({
URL: "request.php",
Global:false,
Disables global Ajax events.
});
If you want to set parameters for global Ajax, you will use the Ajaxsetup () function. For example, pass all AJAX requests to request.php, disable the global method, and force the Post method to pass:
The code is as follows: $.ajaxsetup ({
URL: "request.php",
Global:false,
Type: "POST"
});
Some of the ways you have to know
Ajax must be written to get the corresponding value from the page. Here are some simple ways to enumerate:
Val ()
The Val () function can return the value of a form's build, such as the value of any kind of input. With the selector action, you can easily get the value of an option group, input box, button, and so on.
The code is as follows: $ ("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 named Pass
$ ("Input[name= ' Save ']:radio"). Val ();//Returns the value of a single option with the name Save
And so on Serialize ()
The Serialize function can help you convert all the values of a Form object to a sequence of strings. This is handy if you want to write a get format request.
Serializearray () is similar to serialize () except that it returns a JSON object.
Thedifference between the Get and post of Ajax
Get mode:
Simple data can be transferred in a Get mode, but the size is generally limited to 1KB, and the data is appended to the URL (HTTP header delivery), that is, the browser appends the individual form field elements and their data to the resource path in the request line as a URL parameter. The most important point is that it will be cached by the client's browser, so that others can read the customer's data from the browser's history, such as the account number and password. Therefore, in some cases, the Get method poses a serious security problem.
Post mode:
When a post is used, the browser sends each form field element and its data to the Web server as the entity content of the HTTP message, rather than as a parameter to the URL address, and the amount of data that is passed by post is much larger than the amount of data that is sent using the Get method. In short, the Get method transmits small amounts of data, high processing efficiency, low security, will be cached, and post instead.
Use the Get method to be aware of:
1 for a GET request (or any that involves a URL pass parameter), the passed arguments are processed first by the encodeURIComponent method. Example: var url = "Update.php?username=" +encodeuricomponent ( username) + "&content=" +encodeuricomponent (content) + "&id=1";
Use the Post method to be aware of:
1. Set the header's Context-type to Application/x-www-form-urlencode to ensure that the server knows that there are parameter variables in the entity. The setRequestHeader ("Context-type", "application/x-www-form-urlencoded;") of the XMLHttpRequest object is usually used. Cases:
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
2. The parameter is the key value pair corresponding to the name/value one by one, separated by the & number for each pair. As Var name=abc&sex=man&age=18, pay attention to Var name=update.php?
Abc&sex=man&age=18 and the name=?abc&sex=man&age=18 of Var are all wrong;
3. The parameters are sent in the Send (parameter) method, for example: Xmlhttp.send (name); If it is get mode, direct xmlhttp.send (NULL);
4. The server-side request parameter distinguishes between get and post. If it is GET mode then $username = $_get["username"]; If it is POST mode, then $username = $_post["username"];
Six, the problem of Ajax garbled
A, the cause of garbled:
1, xtmlhttp the data returned by default character encoding is Utf-8, if the client page is gb2312 or other encoded data will produce garbled
2, Post method submission data The default character encoding is Utf-8, if the server side is gb2312 or other encoded data will produce garbled
B, the solution is:
1, if the client is GB2312 encoding, the server specifies the output stream encoding
2, the server side and the client are using UTF-8 encoding
Gb2312:header (' content-type:text/html;charset=gb2312 ');
Utf8:header (' Content-type:text/html;charset=utf-8 ');
Note: If you have done the above method, or return garbled words, check whether your way is get, for the GET request (or all involved in the URL to pass parameters), the passed parameters must be preceded by the encodeURIComponent method processing. If not treated with encodeuricomponent, it will also produce garbled characters.
Summary of usage of $.get (), $.post (), $.ajax (), $.getjson () in jquery