Last reviewed the XMLHttpRequest object, this time to summarize the other Ajax objects, as well as the various versions of AJAX usage and differences.
formdate
Now everyone in the web will use the form's data serialization, XMLHttpRequest also provides a type called formdata;
var data=new FormData ();d ata.append ("name", "Zhang San");d ata.append ("Age", "+"), Alert (Data.get ("name"));
There is a get and set method, which can be used to get the data and settings data; the Append () method receives two parameters: the key and the value, corresponding to the name of the form field and the value contained in the form field, respectively. You can add as many key-value pairs as you like. You can also pass in form elements to the Formdata constructor.
var data=new FormData (Document.forms[0]);
Timeout Settings
IE8 later adds a timeout property for the Xhr object, which indicates that the request terminates after waiting for the response in milliseconds, and after setting a value for timeout, the timeout event is triggered if the browser has not received a response within the specified time. The OnTimeOut event handler is then called.
Xhr.onreadystatechange = function () { if (xhr.readystate = = 4) { try{ var s = xhr.status; if (s>= && s <) { //success (XHR); } else{ //failure (XHR); } } catch (e) {} }else{}}; Xhr.open (); xhr.timeout = 1000; Xhr.ontimeout = function () {
The Status property of the XHR after timeout has an exception, so add try catch.
Overridemimetype () method
Firefox is the first to use this method to override the MIME type of the XHR response.
This is useful for servers and clients that use different encoding types. For example, if the browser uses UTF-8 and the server returns data in GBK format, it may experience garbled characters. And now it can be solved with overridemimetype.
var xhr = new XMLHttpRequest (); if (xhr.overridemimetype) { //overridemimetype () must be set before send () Xhr.overridemimetype ("Text/plain; Charset=utf-8 ");} Xhr.open (' GET ', url,true); Xhr.send (null);
At this point the server will prioritize using the format specified in Overridemimetype () to send a response to the browser.
In this case, even if the service-side program has already set the header Content-type, the response will be returned using the settings in Overridemimetype () first.
Progress Events
The Progress events specification is a working draft of the network, defining events related to client server communication with the following 6 progress events.
Loadstart: Triggered when the first byte of a response data is received.
Progress: constant triggering during reception of the response.
Error: triggered when a request error occurs.
Abort: Triggered when the connection is terminated because the abort () method is called.
Load: Triggered when the full response data is received.
Loadend: Triggered after communication is complete or triggered by erroe,abort or load events.
Load Event
Firfox was committed to simplifying the asynchronous interaction model when implementing a version of the Xhr object. The Load event is then introduced to replace the ReadyStateChange event. The Load event is triggered when the response is received, so there is no need to check the ReadyState property. The end result is:
Xhr.onload = function (event) {if (xhr.status >= && xhr.status <300) | | xhr.status = 304) {Alert (xhr.res Ponsetext); } else {alert ("Request was unsuccessful:" + Xhr.status);}}; Xhr.open ("Get", "altevents.php", true); Xhr.send (NULL);
basic steps in AJAX programming
There are a lot of Ajax requests now, what get ah, post ah, Ajax AH and so on, but they basically have the following several steps
1) Get Ajax object (XMLHttpRequest) 2) Send request to server using XMLHttpRequest 3) on Server side processing request 4) in the Listener, Processing the response returned by the server the original Ajax programming method
1. Get Ajax Objects
function getxhr () { var xhr; if (window. XMLHttpRequest) { xhr = new XMLHttpRequest (); Non-IE browser }else{ xhr = new ActiveXObject (' microsoft.xmlhttp '); IE browser }
var xhr = getxhr ();
2) Send request
Xhr.open (Request method, request address, asynchronous or synchronous); Request method: Get/post Request Address: If it is a GET request, the request parameter is added to the back of the request address. True indicates an asynchronous request: When the Ajax object sends the request, the user can do other things to the current page. Asynchronous is generally used. False indicates a synchronous request: When the Ajax object sends the request, the browser locks the current page and the user waits for the processing to complete before doing the next step.
Mode one: Get request var xhr = getxhr (); Xhr.open (' Get ', ' Check_name.action?name=zs ', true); Xhr.onreadystatechange=callback; Bind callback function xhr.send (null); Mode two: Post request var xhr = getxhr (); Xhr.open (' Post ', ' check_username.action ', true); If you are sending a POST request, you need to set the message header encoding format to "Application" xhr.setrequestheader (' Content-type ', ' application/ X-www-form-urlencoded '); Xhr.onreadystatechange=callback; Bind callback function Xhr.send (' username= ' + $F (' username '));
3) Generally after the server gets the AJAX request to do their own processing, the end will generally return a result out
4) Writing listeners
function CallBack () { if (myajaxobject.readystate==4&&myajaxobject.status==200) {/ * 2, return format is XML ( responsexml) Processing: *// /Get the server-side generated XML tag name var tag=myajaxobject.responsexml.getelementsbytagname (' Mes '); Gets the text content under the label (required information) var val = tag[0].childnodes[0].nodevalue; $ ("Isexist"). Innerhtml=val; Show return information on page }
the Ajax request method of jquery
jquery deserves to be a great JavaScript framework, for JS to do a lot of encapsulation, here we can simply use the method provided by jquery, and reduce some of our repetitive code, so that we can only care about the business;
$.ajax () This is the most basic step of jquery for Ajax encapsulation, which can be done with all the functions of asynchronous communication. That is, in which case we can perform an asynchronous flush operation with this method. But it has many parameters, let's get to know it.
1.url:
Requires that the requested address be sent as a parameter of type string (the current page address is assumed to be the default).
2.type:
A parameter of type string is required, and the request method (post or get) defaults to get. Note Other HTTP request methods, such as put and delete, can also be used, but only some browsers support it.
3.timeout:
Requires a parameter of type number to set the request time-out (in milliseconds). This setting overrides the global setting of the $.ajaxsetup () method.
4.async:
Requires a parameter of type Boolean, which is set to True by default and all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the synchronization request locks the browser, and the user's other actions must wait for the request to complete before it can be executed.
5.cache:
A parameter that is required to be of type Boolean, which defaults to True (False when datatype is a script), and set to false will not load the request information from the browser cache.
6.data:
Requires data to be sent to the server as an object or a string of type parameters. If it is not already a string, it is automatically converted to a string format. The GET request will be appended to the URL. To prevent this automatic conversion, you can view the ProcessData option. The object must be in key/value format, for example {foo1: "Bar1", Foo2: "Bar2"} to &foo1=bar1&foo2=bar2. In the case of arrays, jquery automatically corresponds to the same name for different values. For example {foo:["Bar1", "Bar2"]} is converted to &FOO=BAR1&FOO=BAR2.
7.dataType :
requires a parameter of type string that expects the data type returned by the server. If not specified, jquery automatically returns Responsexml or ResponseText based on the HTTP packet mime information and is passed as a callback function parameter. The following types are available:
XML: Returns an XML document that can be processed with jquery.
HTML: Returns plain text HTML information, and the included script tag is executed when the DOM is inserted.
Script: Returns plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note When you make a remote request (not under the same domain), all post requests are converted to get requests.
JSON: Returns the JSON data. The
Jsonp:jsonp format. When a function is called using the Sonp form, for example Myurl?callback=?,jquery will automatically replace the latter "?" is the correct function name to execute the callback function.
Text: Returns a plain text string.
8.beforeSend :
requires a parameter of type function that can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If you return False in Beforesend, you can cancel this Ajax request. The XMLHttpRequest object is the only parameter.
Function (XMLHttpRequest) {
this; // The options parameter
}
9 that was passed when the AJAX request was invoked. Complete :
requires a parameter of type function that is called when the request is completed (called when the request succeeds or fails). Parameters: The XMLHttpRequest object and a string that describes the successful request type.
function (XMLHttpRequest, textstatus) {
this; //Options parameters passed when calling this Ajax request
}
10.success : Requires a parameter of type function, the callback function called after the request succeeds, there are two parameters.
(1) The data returned by the server and processed according to the datatype parameter.
(2) A string describing the status.
function (data, textstatus) {
//data may be xmldoc, jsonobj, HTML, text, and so on
this; //The options parameter passed when calling this Ajax request
}
11.error:
The function that is called when the request fails with a parameter that is required as a function type. The function has 3 parameters, the XMLHttpRequest object, the error message, and optionally the error object being captured. The Ajax event functions are as follows:
function (XMLHttpRequest, textstatus, Errorthrown) {
Normally textstatus and Errorthrown only one of them contains information
This Options parameters passed when calling this Ajax request
}
12.contentType:
A parameter of type string is required, and when the message is sent to the server, the content encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.
13.dataFilter :
requires a function type parameter to preprocess the original data returned by Ajax. Provides data and type two parameters. Data is the original data returned by Ajax, and type is the datatype parameter that is provided when Jquery.ajax is called. The value returned by the function will be further processed by jquery.
function (data, type) {
//Return to processed data
return data;
}
14.dataFilter:
A function that requires the preprocessing of the original data returned by Ajax, as a parameter of the function type. Provides data and type two parameters. Data is the original data returned by Ajax, and type is the datatype parameter that is provided when Jquery.ajax is called. The value returned by the function will be further processed by jquery.
function (data, type) {
Returns the processed data
return data;
}
15.global:
Requires a parameter of type Boolean, which is true by default. Indicates whether global AJAX events are triggered. Setting to FALSE will not trigger global AJAX events, Ajaxstart or ajaxstop can be used to control various AJAX events.
16.ifModified:
A parameter of type Boolean is required, and the default is False. Get new data only when the server data changes. Server data changes are based on the last-modified header information. The default value is False, which ignores header information.
17.jsonp:
Requires a parameter of type string to override the name of the callback function in a JSONP request. This value is used instead of the "callback=?" The "callback" part of the URL parameter in this get or POST request, such as {jsonp: ' onjsonpload ', causes the "onjsonpload=?" passed to the server.
18.username:
A parameter of type string that is required to respond to the user name of the HTTP access authentication request.
19.password:
A parameter of type string that is required to respond to the password for HTTP access authentication request.
20.processData:
Requires a parameter of type Boolean, which is true by default. By default, the data sent 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.
21.scriptCharset:
A parameter of type string is required and is used to force the character set (charset) only if the request is datatype as "JSONP" or "script" and the type is get. Typically used when local and remote content encodings are different.
$.ajax ({ type: "GET", URL: "test.do", data: {"username": $ ("#username"). Val ()}, DataType: "JSON", success:function (data) { $ (' #resText '). empty (); Empty all contents of Restext var html = '; $.each (data, function (Commentindex, comment) { html + = ' <div class= ' comment ' >
$.get
Parameters:
URL (String): The URL address of the sending request.
Data (MAP): (optional) data to be sent to the server, expressed as a Key/value key-value pair, will be appended to the request URL as querystring.
Callback (function): (optional) The callback function when loading succeeds (the method is called only if the return state of response is success).
The Get method is simple and implements our GET request in a simple way$.get ("Data.do", $ ("#firstName"). Val (), function (data) {alert (data);//The data returned can be xmldoc, jsonobj, HTML, text, and so on.});
$.postThis function is actually a further encapsulation of the $.ajax, reducing the parameters, simplifying the operation, but the scope of use is even smaller. $.post simplifies the way data is submitted and can only be submitted by post. It can only be an asynchronous access server, cannot be accessed synchronously, and cannot be handled incorrectly. In satisfying these cases, we can use this function to facilitate our programming, it's main several parameters, like Method,async, etc have been set by default, we can not change the
Parameters:
URL (String): The URL address of the sending request.
Data (MAP): (optional) data to be sent to the server, expressed as a Key/value key-value pair.
Callback (function): (optional) The callback function when loading succeeds (the method is called only if the return state of response is success).
type (String): (optional) The official description is: Type of data to be sent. The type that should actually be requested for the client (Json,xml, etc.)
$.post ("Ajax.do", {name: "Lulu"},function (data, textstatus) {//data can be xmldoc, jsonobj, HTML, text, etc. And soon.//this; For the option configuration information for this AJAX request, please refer to the Thisalert (data.result) mentioned in Jquery.get (). }, "json");
$.getjson$.getjson ("Test.js", {name: "John", Time: "2pm"}, function (JSON) {alert ("JSON Data:" + json.users[3].name);});
This is a further encapsulation, which is to manipulate the return data type as JSON. Inside the three parameters, we need to set, very simple: url,[data],[callback].
Angularjs's ajax approach $http service, $http service simply encapsulates the Browser He is similar to the $.ajax () method of jquery;
Personally think that angularjs in the implementation of Ajax this piece does not work, first can not set whether synchronization, and the syntax is not very simple and understandable.
$http. Post (' do-submit.php ', myData). Success (function () { //Some code});
Of course, there are simpler get and post requests;$http. Post (Bootpath+url+prefix, Angular.tojson (param)). Success (function (Result) {}}). Error (function (err) {} ) ;
It's best not to use ANGULARJS if you can use jquery's AJAX requests.
All right, okay. This article summarizes some of the new features of the Ajax XMLRequest2 class, and then there are some ways to use ANGULARJS. In the head of Ajax finally have a concept, not after the silly send request.
Ajax Usage and differences