In-depth research into a technology to understand the details of using these technologies is ultimately a matter of choosing what to do when we want to use these technologies to solve a specific problem. If there are two technologies that will allow us to achieve the same goal, we would not naturally compare the differences between them, and by combing these differences we can draw a conclusion as to how we should choose when we use them.
In the previous article, I talked about XMLHttpRequest can control the headers of HTTP requests more precisely, so I'm going to find out if I can control HTTP headers like XMLHttpRequest in a synchronous commit, Finally I found that we can set the META tag in the head of the HTML, and use HTTP-EQUIV to set the header information of the HTTP, but Meta header information is actually the server to the browser's response header information, rather than request header information, the following is our most commonly used, The meta-notation that best affects the page display, as follows:
<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8" ><meta http-equiv= "Expires" content= "31 Dec 2099 ">
This header is telling the browser that the page is an HTML document, the character set is UTF-8, and also tells the browser that you want to cache this page in the browser, if the user does not clean the browser cache, then the page can be read from the cache before December 31, 2099, You do not need to download the entire HTML document from the server.
Expire is the server-side specified browser caching behavior, in the Web front-end optimization It represents the cache capacity is very important, Ajax can also use the browser cache, but this piece of knowledge needs to be related to what I want to say, so let's put it aside for a moment.
Content-type in the previous article many times, we develop the page, the HTML head of this property is a familiar stranger, in many of the IDE used to develop the page, we choose the template to create a page, this tag is the default, we do not have to add it ourselves, But I have been developing my experience for many years and I have really encountered the technical problems of improper use of content-type.
A friend of mine earlier asked me a question like this, their company has a Web application, this Web application does not have too many pages, mostly background programs, the purpose of the system is to provide their company users with some special services, If users want to use the service only in their own site pages across the domain to request their system-provided web pages, in order to ensure the security of the system, this friend's system will be sent to the user to do a lot of security checks, this check is more time-consuming, but very important, so they to give end users a friendly user experience, Just when the security check is being processed to provide a waiting page, perhaps because this friend developed a system server is too heavy and the page is too small too simple, not particularly good at the development of the page they do not write a separate waiting page, Instead of waiting for the page to be placed in the background of the servlet directly constructs (in fact, in the background directly spelled the page string), but they construct time forgot to add the Content-type attribute in this simple page, hateful is this friend's system test time did not find any problem, The scary thing is that after the production environment, some users who call their systems in the IE browser page directly display the source code instead of the page, but it is normal under the non-IE browser. Not all people have problems, there are problems are part of the browser, in their own test environment and simulated no problem, this how to do, that friend's project team spent two days did not understand how, and then the user's complaints are more and more, if he asked me have encountered this situation? At that time, I used IE and non-IE grab bag tool compared to the HTTP request in different browser header and response header, found the difference: Some browser content-type is text/html, some Text/plain,ie browser is Text/plain, Non-IE two kinds have, but if the IE is text/plain, then the page will show the source code, if I see the phenomenon I told this friend, the friend check the code found that they are constructing wait for the page did not specify the Content-type header, if they are forced to specify the header text /html, the problem is solved. Although the problem solved, but we still did not find where the problem, why the test environment can not reproduce problems, this phenomenon for the Internet development of friends may well understand that the Internet application deployment of the network environment is very complex, the user sends an HTTP request from the browser to the server , this process is not directly to the Web container like Tomcat,jboss as we normally develop, but passes through many paths, the most common CDN, load balancer device, static resource server such as Apache and so on, the request through these links have the authority and ability to change the HTTP message, If your site is larger, the network environment will be more complex and it is almost impossible to find aA person who knows all these details, so in the Internet company will have a pre-release environment, this environment will do their best to simulate the real environment, although this environment is also for testing, but many companies pre-release environment is available in the external network access, if the pre-release environment design is good, it can be effective to ensure the security of the system after the production But the most effective way to avoid the above problem is to own technology, experience to perfect.
Content-type is very useful, more understanding of it can solve more doubts for us, detailed explanation of this property is not the subject of this article, below I give interested friends two links, interested can see:
Http://baike.baidu.com/view/1547292.htm?fr=aladdin
Http://tool.oschina.net/commons
Most of the time, in the synchronization request we send the HTTP request to the server is not need to understand too much content-type role, in fact, many HTTP headers do not care too much, but there is something especially like our use of Chinese characters rather than English, the encoding of the character set is to pay more attention to.
Although the HTML header setting charset encoding is UTF-8, this is the character set of the response header, but if we then make HTTP requests with this response page, Then this encoding level will affect the character encoding of the commit request, i.e. if we do not specifically specify then all requests on this page are followed by that encoding level. So the question is, if we want to request from a UTF-8 page a background can only receive GBK encoded data interface, then how we change the encoding of this request, the problem is further, how can we control the request HTTP header in the synchronization request, is at least a very important content-type attribute?
The synchronous commit core is the form, which, like the core of Ajax is XMLHttpRequest, has an attribute accept-charset under the form tag that specifies the character set that the server accepts for processing form data. The Accept-charset property allows you to specify a series of character sets that the server must support to correctly interpret the data in the form.
The value of this property is a list of character set names enclosed in quotation marks. If the acceptable character set does not match the characters used by the user, the browser can choose to ignore the form or treat the form differently. The default value for this property is "unknown", which means that the character set of the form is the same as the character set for the document containing the form. However, this property in IE is not good, and sometimes invalid, so if the developers will be excluded from the coding error, but the requester and the responder agreed to do such conversions, the conversion of the character set on the server to do the best.
The form form also has an important property that has a significant effect on the HTTP request, which is enctype, which contains three values, as follows:
Value |
Describe |
application/x-www-form-urlencoded |
Encode all characters before sending (default) |
Multipart/form-data |
Character encoding is not. You must use this value when you use a form that contains a file upload control. |
Text/plain |
Spaces are converted to "+" plus signs, but special characters are not encoded. |
The value of the first row I mentioned many times in this article, and now we know what it does in the browser, The form form Enctype The default property value, which allows the browser to encode the requested data before the request is sent, why does the browser encode the request data? The root cause is because the computer is invented by the Americans, the Americans use the English alphabet to input data to the computer, and like we Chinese people use characters kanji, and the Chinese character for the computer is a special character, can not use a few letter combination simple expression, look at the global, this problem not only occurs in Chinese characters, Korean, Japan and other non-letter language will have the same problem, but the network transmission of data are binary, in order to make the request data on the server can be correctly restored server server must have a character set to accommodate all languages in the world such as UTF-8 or unique character Set GBK specification escaped, This is the role of application/x-www-form-urlencoded, he tells the browser you want to transcode the request data. Form form can also transfer files, files need special parser to parse, sample to Picture parser, Word document to Office parsing, but these files themselves are binary, and is unique binary, so the network transmission time best to stay the same as the multipart/ Form-data properties, sometimes we do not want to transcode, then we can use Text/plain, these parameters will be reflected in the HTTP request header Content-type attribute.
This shows that the form form is not so simple, it also helps us to develop shielding a lot of technical details, so when we do not use form form to submit synchronization requests can fall into these details traps, the most common problem is to use a non-form submission of a GET request, the GET request will be passed to the server, And this parameter contains Chinese, for example: Websit= Blog Park, if we write directly, the browser will not give me an error, but to the server after we will find that parameters become garbled, URL caused by garbled is to let a lot of beginners headache problem, but JavaScript has long been expected, As it provides three pairs of functions that can encode strings, respectively: Escape,encodeuri,encodeuricomponent, corresponding 3 decoding functions: Unescape,decodeuri,decodeuricomponent. The root of the problem is that our submission request loses the protection of the form, and we must manually specify the functionality provided by Enctype in the form. About the above three on the function, this article does not do too much to tell, want to know the friend can ask degree Niang.
The above content is what I told the synchronization request when the content, here to make up, by the above content we can see that the synchronous commit to the HTTP header control ability is very poor.
XMLHttpRequest has a strong control over HTTP headers, which can be set by setRequestHeader (name, value) to the HTTP request header, method getResponseHeader (first name) gets the specified header, Method Getreponseheaders () gets all the response header information, although the HTTP request header is not visible to the user (the user only cares about the content of the HTTP request, because the request is what the user needs), but for the developer the HTTP request header is very important, Because the HTTP request header is the leader of the entire HTTP, we can control the HTTP request header information to achieve the goal that many traditional HTTP requests cannot achieve.
When using XMLHttpRequest, if we do not make any changes to the request header, by default the browser sends the following HTTP header information to the server, respectively:
Accept: Content types that the browser can handle; Accpet-Charset: The browser is able to display the character set; accept-Encoding: The compression encoding that the browser can handle; accept- Language: The language currently set by the browser, Connection: The type of connection between the browser and the server, the Cookie: any cookie;host of the current page setup: the domain where the request page is made; Referer: the URL of the page that made the request. User-agent: The client Agent string for the browser.
The above nine header information is transmitted by all browsers, but the header information may be slightly different depending on the browser type.
Although the setRequestHeader method can modify the HTTP header information, if we modify some of the above 9 properties, we will find that this modification sometimes does not help, this is some browsers for security reasons do not let developers easily change, Fortunately, the setRequestHeader method can also customize the request header, if we want to do some special processing related to the request header, it is best to define the request header. In addition, the setRequestHeader method is used after the open method, before the Send method, otherwise it will not reach the effect.
Next is another point in AJAX technology: The use of callback functions. Here's a word: The Ajax callback function is used to handle the HTTP request response, that is, the server has given the browser request results to invoke the Ajax callback function, is that right? I think a lot of people will think this sentence is correct, here I do not tell you the answer, first talk about the use of Ajax callback function, we see the following code:
xmlhttp.onreadystatechange=State_change; function State_change () {if (xmlhttp.readystate==4) {// 4 = "Loaded" if (xmlhttp.status==200) {// = OK / ... our code here ... } else { alert ("problem retrieving XML data");}}}
XMLHttpRequest's onReadyStateChange method is used to receive the callback function, in the callback function we want to judge the value of readystate to 4,status value of 200, we think we have a successful response, Otherwise, there is no successful response. Once I tried to get rid of the xmlhttp.readystate==4 code, I found that the alert in else was executed several times and the request was still handled correctly after the dialog was finished. This illustrates a problem: The onReadyStateChange method is related to the readystate value, and onreadystatechange is executed whenever the readystate value changes. In fact, from the name of onReadyStateChange can know this.
The value of readystate in XMLHttpRequest is as follows:
Value 0: Uninitialized that has not yet called the Open method, the value 1: Start that has called the Open method, but has not yet called the Send method, the value 2: Send is called the Send method, but has not received a response, the value of 3: Receive that has received the partial response data, Value 4: The completion is received The full response data.
This shows that the Ajax callback function is not only triggered when the response time, an AJAX request to record the callback function onReadyStateChange method will be called 5 times, so we must use readystate==4 to indicate the success of the response. In addition, from the ReadyState state value we can also find that the assignment of the onreadystatechange attribute should be placed before the open method, otherwise your writing is a hidden problem.
Having learned this, we look at the use of jquery's AJAX approach, which is the encapsulation of the browser's underlying AJAX operations, which masks the differences between browser implementations and provides methods that are the upper-level encapsulation of the underlying AJAX operations, He can make it easy for those without a deep understanding of the original Ajax principles, here we focus on the use of Ajax callback functions in jquery, here's what I excerpt from the jquery Document:
If you are working with $.ajax () data, you need to use a callback function. Beforesend, error, Datafilter, success, complete. Beforesend is called before the request is sent, and a xmlhttprequest is passed in as a parameter. Error is called when the request is faulted. Incoming XMLHttpRequest object, a string describing the type of error, and an exception object (if any) Datafilter called after the request succeeds. The returned data is passed in as well as the value of the "DataType" parameter. and the new data (possibly processed) must be returned to the success callback function. Success called after the request. The data after the incoming return, and the string containing the success code. Complete the function is called after the request is completed, regardless of success or failure. The incoming XMLHttpRequest object, and a string containing the success or error code.
The success method above is the case that the value of the readystate value is 4,status 200 (the actual status will be more points, and then talk about this problem), complete is a function called after the request is completed, this method is not related to the status value , only with the readystate value of 4, Beforesend is the readystate state is 1 times use, the error method is more complex point, it is a comprehensive error consideration, anyway, is unsuccessful is an error, Datafilter is a corresponding conversion of the returned data based on the type of user-defined response data (DataType), which we rarely use, which is done internally by jquery, but this callback is executed before the success method.
The Datafilter callback function can handle the response data, which leads to a new problem, what types of response data we get through XMLHttpRequest, XMLHttpRequest has two properties to store the response data, One is responsetext: The text type of the response data, is actually the string, responsexml:xml the document type response data, the property only in the HTTP response header is text/xml or application/xml when the browser will help us transform , which is null if it is not the above type.
When we use jquery's ajax approach, we get richer response data by setting the DataType property, and here's the content of the jquery document that I extracted, as follows:
DataType: Expected data type returned by the server. If not specified, JQuery is automatically judged intelligently based on the HTTP packet mime information, such as the XML MIME type being recognized as XML. In 1.4, JSON generates a JavaScript object, and script executes it. The data returned by the server is then parsed against this value and passed to the callback function. Available values:"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:" on a remote request (not in the same domain), all post requests are converted to get requests. (because the script tag of the DOM will be used to load)" JSON: Returns the JSON data. "JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function. "text": Returns a plain text string
Most of the above operations are done by jquery, if we define the Datafilter callback function, which is executed before the type conversion, that is, the data of the Datafilter operation is the original data returned by Ajax.
When the readystate value is 3, we will do some unexpected functions, readystate 3 of the state is very special, this time the server has given the response, but the response data is not all sent to the browser, But at this point you operate responsetext will find that there is data, but this data is not complete, I have seen the use of XMLHttpRequest this attribute has been made two effects, as described below:
effect One: Although we are doing our best to make the request and response time shorter, but some request processing is not fast, for example: Upload a file or a browser to receive large data, if the scene is the latter is the user request data is very small, but the reception of data is very large, the reception time is very long, We generally do a wait for request processing effect, if this effect can have a precise progress bar, then to the user's experience is very good, HTTP response message header has a property is Content-length, this property tells the browser the size of the entire response, the General browser received a response, Even if the response is only part of the data, the response header will be sent first, the reason is to let the server know how much data received to indicate that the reception is complete, So when readystate is 3, we can calculate the size of the received response and compare it to content-length to know that the response received that stage, so the progress bar will be very accurate.
effect Two: This effect is I have been inadvertently seen a foreign web site discovered, unfortunately I do not remember the URL now, the author of the Web page also study the characteristics of Ajax, he through the AJAX request an article, and then this article will be displayed in a row of the page, Because this effect can be done in the browser using the SetTimeout function, the author controls the service-side data return time, which is displayed on the page as soon as the browser receives some data.
However, there is a feature of this operation, that is, developers will define a callback function, using the SetTimeout function polling the callback function, SetTimeout and callback function is used in the onreadystatechange callback function, And the string to receive the data to be stored with public variables, so this effect is still a bit difficult, because the readystate state is 3 when the callback function can only be called once.
In the Ajax method of jquery There is an attribute ifmodified, and the document is interpreted as:
false) Get new data only when the server data changes. Use the HTTP packet last-modified header information to determine. In jquery 1.4, he also checks the server-specified ' ETag ' to determine that the data has not been modified.
This parameter shows that AJAX technology can operate on HTTP caching, so some JavaScript books explain Ajax when the request succeeds using two response codes, one is the common 200 and the other is a 304,304 response code indicating that the response of the request is to be taken from the browser cache , the server does not need to be returned directly.
In order to clarify the Ajax operation Cache, we first need to know the browser caching mechanism, in the Web front-end optimization using browser caching is a very important rule, then how to let the browser can cache our response? There are generally two ways:
mode one: through expires, Cache-control to control, the former is the specific date of the specified cache expiry, the latter is the specified cache after how long expires, for example, 10 years after the expiration, we first request a resource success response code of 200, This time the response will return a last-modified back, if the resource we set the cache, then the second request in the request will send the If-modified-since property, the value of the property is the first return of the last-modified, After receiving the server, the server returns a 304 response code and the 304 response code tells the browser that the response results are taken from the browser cache.
mode two: using Etag,etag is another cache invalidation mechanism, the server that uses the etag calculates a hash value for the specified resource (typically MD5), and the server returns the value to the browser the first time it is requested. The second request browser will send this value to the server, the server by computing the hash value of the resource and the value of the comparison, if the value is equal to indicate that the resource has not changed, then the server will give a 304 response code to the browser, let the browser in its own cache to find the corresponding response.
Either way, if the request has been cached, the server will return 304 response code, using the browser cache does not mean that the browser does not send the request, whether the browser cache is the server to command, but the 304 request does not return the response body, only the response header, and the request is a get, the request is very small, The speed is very fast.
Also, when Ajax receives a 304 response code, AJAX takes the response from the browser cache, and the operation XMLHttpRequest will help us out.
However, it is important to note that for 304, a request that can be cached by the browser is only a GET request and the original request must be a GET request, and the POST request cannot be cached by the browser.
XMLHttpRequest is very strong, I am strong here is to say that it can do in addition to asynchronous request also can do synchronous request, before I said onReadyStateChange, said ReadyState, in fact, these two things should be able to say that specifically belongs to the asynchronous request, why? In the previous article I talked about the author of Nodejs's choice of JavaScript language because of the JavaScript callback mechanism, because there is a callback can make single-threaded JavaScript asynchronous effect, since it is synchronous commit, the definition of the callback function is still meaningful? So if we use xmlhttpquest to do a synchronous request, our code can write this:
Xmlhttp.open ("GET", URL,false); Xmlhttp.send (null); if (xmlhttp.status==200) {// = OK / ... our code here ... } else { alert ("problem retrieving XML data"); }
The code executes sequentially, blocking the page execution if the request is slow.
See here is estimated that some people will have doubts, Ajax synchronous submission is valuable? This is not as good as using a form to do synchronous submission, this to specific problems, I mentioned in the previous traditional synchronous submission of HTTP precision control is very poor, if some synchronization request we need more HTTP control then use AJAX better, in addition to the traditional synchronous request response is to overwrite the original page, It is either a new form to receive the response, but the synchronous Ajax is more flexible in responding, compared to Ajax synchronization requests.
In jquery Ajax there is a property that is timeout, you can set the time-out for Ajax requests, before I explain Ajax technology, we will find that XMLHttpRequest does not have a property to set this time-out property, In fact, in IE8 including IE8 and above, XMLHttpRequest has a timeout attribute, other browsers do not, but XMLHttpRequest has an abort method, which can cancel the asynchronous request, remember that it is an asynchronous request, Synchronous operation This method is invalid, the reason is invalid because we do not have the opportunity to execute the method under synchronous submission. With this method, we can simulate the AJAX request timeout.
Oh, wrote more than 8,000 words, it seems that this article also can not finish my topic, this shows the page of the way to submit data is very big knowledge.
Explore Web page Sync submissions, Ajax and Comet Secrets (medium)