The technology in the headlines is the most common technology in web development, but I think the many details of these common techniques are not quite clear to many friends, and understanding these details is a key to mastering these technologies, and today I'll talk about the details of what I've learned with these techniques.
Synchronous commit means that the data entered on the page is submitted to the server by performing a submit operation on the form form of the page, and the server finishes processing the data and returns the resulting information to the page.
When we use synchronous commit, there is an indispensable element, that is, the form tag, the form tag represents a boundary, in the form range of elements such as Input,select, after the form executes the Submit event, The data they record is transmitted to the corresponding server by the browser using the HTTP protocol, either post or get.
So how do we perform the submit operation of the form? The browser provides us with four ways to:
Way One:
<input type= "Submit" value= "Submit"/>
Way two:
<button type= "Submit" >Submit</button>
Way three:
<input type= "image" src= "Submit.gif"/>
Mode four:
<form id= "frm" name= "frm" ></form>document.getelementbyid ("frm"). Submit ()
Here the most special is the way three, in a form tag contains a type image element, its effect and a submit button incredibly similar, this estimate many people did not find.
However, from my years of experience, the essence of the first three ways is the same, should be classified as a class, and the fourth way flexibility is the most common, in the actual development we'd better only use the fourth way, discard the first three ways, in order to let my recommendations from the persuasive, I will tell you the disadvantages of the first three ways.
Cons One: Form forms are automatically submitted.
The automatic submission of forms is usually when we enter information on the page, accidentally hit the ENTER key, the specific point is when the form form under the input elements (such as: text box, Password box, drop-down box, radio box, etc., but textarea text field except) to get the focus, This time you press the ENTER key to cause the form form to be automatically submitted. To prevent this from happening, we will rewrite the form as follows:
<form name= "Form1" method= "Post" onsubmit= "return false;" >
Onsubmit= "return false;" You can let us stop the form form auto-commit behavior, although we have the means to solve this problem, but we do not know what causes this problem, in fact, the root cause of the problem is that we have developed a page in the first three ways of one of the ways, These special elements that are used to submit form forms are the culprit for the problem.
Disadvantage two: When the user completes the page after the data, the user then executes the submit operation, today's website almost does not allow the user to submit the data directly to the backstage, for all sorts of reasons, we must check the data before the browser submits the data or the conversion of some data format.
Because of the reasons above, we have to add a verification method on a submit-capable label, which is often tied to a click event, which seems to be fine, but sometimes we find that the page does not pass the test, The reason for this is that we found that the server received two of the same HTTP requests, and I found that many of the friends who have been developing for many years are not very clear about the cause of the problem, and perhaps the solution to this problem is as good as the solution offered by the above disadvantages, perfect, and perfectly preventing us from seeking the truth, The solution to this problem is to change the type of the button to a button, while not using the buttons that come with the Submit function in form form, but rather the way asphyxication submits form forms.
Submitting form forms with the submit feature element will cause duplicate submissions because the elements themselves have a default click event, which is used to perform a submit operation, and if we add a check to the Submit button, the Click event is used. If we accidentally wrote a form.submit in our code, the result would be to have the form form executed two times. Of course there is a way to block the default event in a click event: Evt.preventdefault (), so that the button does not execute the default submit event, which is often the case when we use a tag, so we will often see this in a tag href= " Javascript:void (0) ", the purpose of which is to prevent the a tag from performing the default href attribute of the Click event, also for a tag evt.preventdefault () is also valid, it can also block the default event of the a tag.
Mode four uses the JavaScript language to control the submission of form forms, so the combination of mode four and JavaScript code is best, and today's Web pages use a lot of JavaScript code to enhance the intelligence of the page. Do not hesitate to use the program four to do the form of the submit operation, should now be used as a convention to execute.
However, there are a lot of scenes can only use form form and server interaction, this exclusive scenario is compared with the Ajax technology to arrive, if you want to explain the reason, we have to talk about Ajax first, so here we sell a xiaoguanzi, wait until the Ajax technology explained, We're going back to talking about scenes that can only use form forms.
Ajax, the name is an abbreviation, its full name should be called Asynchronous Javascript+xml technology, its emergence of web front-end development has epoch-making significance, formally because of Ajax, enhance the role of the browser in the Web application, Requires a more professional web front-end engineer specializing in web front-end development.
The core of Ajax technology is the XMLHttpRequest object, the XMLHttpRequest object is a JavaScript built-in object, but the version below IE6 (including IE6) needs to be created using ActiveXObject mode. About the usage of XMLHttpRequest I think as long as the AJAX applications are very familiar with and clear, so I do not want to XMLHttpRequest to do too much description, but still want to post a code, so that I can tell the next.
The code is as follows:
<script type= "Text/javascript" >varXMLHTTP;functionloadxmldoc (URL) {XMLHTTP=NULL;if(window. XMLHttpRequest) {//code for all new browsersxmlhttp=NewXMLHttpRequest (); }Else if(window. ActiveXObject) {//code for IE5 and IE6xmlhttp=NewActiveXObject ("Microsoft.XMLHTTP"); }if(xmlhttp!=NULL) {Xmlhttp.onreadystatechange=State_change; Xmlhttp.open ("GET", URL,true); Xmlhttp.send (NULL); }Else{alert ("Your Browser does not support XMLHTTP."); }}functionState_change () {if(xmlhttp.readystate==4) {//4 = "Loaded" if(xmlhttp.status==200) {//K = OK //... our code here ... } Else{alert ("Problem retrieving XML data"); } }}</script>
The above example is a request to perform a get using AJAX, the code for this operation is as follows:
xmlhttp.onreadystatechange=State_change; Xmlhttp.open ("GET", url,true); Xmlhttp.send (null);
These three lines of code are still very learned, some of the details may be a lot of friends understand is not too clear, I will tell the details below.
details One : Open method, open method has three parameters, The first parameter is the way HTTP requests, XMLHttpRequest commonly used in two ways: Get and post, the second parameter is the URL of the request, if you use the XMLHttpRequest object to perform a get operation, then you have to organize the parameters in the URL, The meaning of the third parameter is "whether to send the request asynchronously," the third argument I enclose in parentheses, want to express is the third parameter actually many friends do not understand it correctly, this parameter can pass two values: True and False,true represents the asynchronous send request, false represents the synchronous sending request, So there's a problem here. What is called an asynchronous send request, what is a synchronous send request? In fact, the meaning of asynchronous and synchronous in XMLHttpRequest is whether the Ajax execution blocks the execution of subsequent JavaScript code, and if we choose synchronous execution, then Ajax executes the HTTP request. Other JavaScript code must wait for HTTP execution to complete when the request responds and the response results are processed so that other JavaScript code can execute, if we choose asynchronous execution mode, Then Ajax executes the HTTP request without blocking other JavaScript code execution that is AJAX execution HTTP request after the browser will be a separate thread to wait for this HTTP response, the current thread can immediately execute other JavaScript code, Wait for the independent thread to get the HTTP response and then to queue the UI thread to execute the AJAX callback function. This is also the principle of using AJAX to solve blocking scripting problems in my previous article.
detail Two : About the Send method, the Send method parameters only one is send (body), in the use of the Get method to submit the request, the Send method passed the null value, if we use the Post method of submission we will put the parameters in the Send method parameters, For this difference a lot of friends are not very clear, because we do web development, whether the get mode or POST method will pass parameters, why Ajax will be a separate send method to pass parameters? To explain this, we have to start with the HTTP protocol, we know that the HTTP GET request parameters are placed behind the URL, and post will not, in fact, this difference is not only from the phenomenon we see, to the HTTP message organization is not the same, GET request parameters are integrated with the URL, While the HTTP message record URL location is the HTTP header, while executing the POST request, the HTTP message will be organized when the URL and request parameters are separated, the URL is placed in the HTTP header, the request parameters are sent as part of the message body to the server, One of the functions of the Send method is that you can fill in the request parameters into the body of the HTTP message, so the GET request cannot use Send to pass parameters, because get does not need to transfer parameters in the body of the HTTP, only post can use the Send method to pass parameters. This shows that the XMLHttpRequest object provides developers with more precise control over HTTP requests, which cannot be given by traditional form form submission methods.
Detail Three: This detail is also a question about the Send method, but this detail and the Post request method is more closely related, so here I first give a kind of post request writing:
Xmlhttp.open ("POST", url,true); // POST request to set the request header yourself Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); // send data and start interacting with the server // Post send request Xmlhttp.send ("Name=sharpxiajun&city=shanghai");
In general we use the POST request submission time, to set the HTTP header content-type to application/x-www-form-urlencoded, The request parameters of send are organized in the form of a GET request that is encapsulated in a parameter after the URL. Why does Ajax have to do this?
I remember a few years ago I consulted a friend about the answer to this question, and he told me that the POST request for Ajax was to impersonate a form form to perform a POST request, The form form, when used for post submission, content-type the HTTP request header to application/x-www-form-urlencoded, when he wrote an example to illustrate the problem. Although the problem has been answered, but it makes me feel xmlhttprequest more mysterious, why Ajax do the POST request to emulate the synchronous form form of the POST request? Does it make a POST request of its own? And even worse, I didn't think of it until recently that Ajax did not provide a way to submit non-simulated form forms.
Where is the source of this confusion? First of all, we think about how we perform post operations without Ajax, only one answer is to use form form, but there is no other way, in contrast to get is different, get the request is the URL and parameters into one, such as the following:
Www.cnblogs.com? Name=sharpxiajun&city=shanghai
JavaScript's built-in objects have many ways to manipulate URLs, the most typical of which is:
Location.href = URL
If we add parameters after the URL, the parameters can be obtained by the server, but the process does not use the form form.
In the era of synchronous submission, the browser executes a POST request only through a form, but this form does not only handle the post, but the Content-type is set to application/whenever we use the post to submit the form. x-www-form-urlencoded, does this parameter simply let the receiving server know that the request is using post to submit the data?
We know that HTTP uses the Get method to pass parameters, the parameter will have a length limit, which is mainly the maximum length of the URL constraints the length of the parameter, but the use of post is different, post will put the parameters in the HTTP request body, in principle there is no length limit. Think we often use the browser to download images, upload images, and even use the browser upload to download oversized video files, which is due to the request data placed in the HTTP file body, so the use of Post HTTP request we can transfer any data, data format is not limited to text, Then if one day we want to use form form to transfer a file, the file in the network will be transferred to the binary, and so on to the server and then need to transcode, restore files, these operations can only be done in the POST request mode, so the post is more complex than get, In order to let the service side know this complex situation, we must tell the server that this situation occurs, so the form does a POST request will appear to specify the Content-type problem, the server receives this content-type to understand, the request data situation can be very complex, Be aware of that.
To Ajax, we also need to execute the POST request, but the Ajax Post request method is to simulate the form form of the Post method, so that the purpose is to take care of the server's feelings, the original page post submission situation for the service side is very complex, If Ajax is a new way to submit post data, then not all Web servers will be version upgrade, so the result is that the lower version of the Web container can not enjoy the convenience of Ajax, the disadvantage of doing so is self-evident, So we want the Web server to treat all post requests equally.
However, does the XMLHttpRequest operation Ajax request really only simulate form form submission method This kind? The answer is really not, in fact, using AJAX to do post requests we can absolutely not need to use the simulation form form submission method, I recently encountered this problem in development, I developed a new system in order to ensure the security of the system, Put forward a request: all pages submitted to the service side of the request if it contains the request parameters have to put Content-type to Application/json, if not Application/json request, will be rejected, heard that this is the system specification, test, Where the fuck is the norm ah, as I developed the time to change the content-type, the result is the service side incredibly receive request parameters, but through the Firebug grab bag, browser request successfully sent, this head big, the problem is where? Where does the request data loss occur?
In the end I found the cause of the problem, is the Send method, when using the Send parameter we will write Xmlhttp.send ("Name=sharpxiajun&city=shanghai"), the name value pairs with = Division, the different name value pairs with the & number division, This parameter form is called serialization, in jquery There is also a method of serialization, in the use of form form synchronous submission method, we do not consider the parameter serialization, because the browser will help us do this thing, However, there are traces in the synchronous submission that tell the browser to do the serialization, such as the way I mentioned above to commit a GET request using a non-form form, but with Ajax we have to do it ourselves, and people who use jquery often ignore the background of serialization, Because jquery lets us get used to submitting data in JSON format, it's important to learn the basics of JavaScript. The serialized data to the service side, the Web server will help us to parse the name value pairs, but when we change the Content-type value, the Web server will not do this thing that the parameters are not parsed, so in Java servlet we can not be in the traditional way to get parameters , but the parameters do not disappear, but the parsing method is not correct, so finally we rewrite the Ajax:
Xhr.setrequestheader ("Content-type", "Application/json; Charset=utf-8; " ); var _param = {}; Xhr.send (Json.stringify (_param));
Instead of serializing data, send uses a JSON-formatted string so that the Web server does not parse the data by serialization, but rather parses it through JSON.
This shows that XMLHttpRequest gives us more flexibility in manipulating HTTP requests.
Detail Four: This detail is still the issue of the Send method, the send parameter in the official document can accept two types of parameters one is XML, one is a string, in the preceding example we are all using the string, instead of using XML format, I would like to experiment with XML format, unfortunately, I have not done this thing, so this article dragged for a long time did not publish, today think about it, do not experiment, let read the article of the Daniel to try.
Recently read an article, which wrote that the parameters of send can be the form of the DOM of the form can be passed the parameter Xhr.send (document.getElementById ("frm"), this practice I have not tried, but this description will affect my description of the following , if my form contains file upload input, does this post request submit the file data to the backend server?
Now we throw away the parameter type of the send non-string, assuming that our XMLHttpRequest can only pass the string, then we can't use Ajax to submit the file data to the server, in other words XMLHttpRequest cannot upload the file. I wrote an ajax file upload framework early, using hack technology to simulate asynchronous file upload operations, which is the principle of constructing a hidden form form and a hidden iframe on the main page, and I copy the elements from the form into the hidden form. Then submit this form, the hidden form request response is received by the hidden IFrame, and then by manipulating the response data of the IFRAME to complete the Ajax asynchronous file upload simulation.
Hack technology is very happy to write a sense of accomplishment, but if there is a natural Ajax asynchronous submission method is the most suitable for production development, the original details of four is to point out that Ajax can not do file upload operation, but after consulting the data found may be I did not find the right way, this need me to further study, Because I have not practiced, but in order to keep the content of rigorous, I still want to mention their doubts, if the result is xmlhttprequest really can not do so, then I also give the way to simulate asynchronous file request, double benefit, in fact, sometimes no answer to think can give people to grow.
Detail Five:Ajax X is intended to be XML, with the development of AJAX technology, we use XML in Ajax is not too much, the replacement of XML technology is a better use of JSON, why this change?
I mentioned that the Send method also has a parameter type is XML, but in fact we almost forget it has this parameter, because it is not very easy to convert a string of XML-like strings into real XML, and different browser constructs XML is still a difference, this may be some friends see will not understand , because a lot of people know that HTML is a subset of XML, I can actually boast that JavaScript and XML are not really fused, but the fact is, JavaScript generates XML is a obscure technology, While the JavaScript specification does specify how to generate XML, there are few real uses in real-world development, so note that this paragraph generates XML by using JavaScript to construct XML, not parsing XML using JavaScript.
When the data returned by the server is XML, the JavaScript operations XML becomes simpler, and we can directly translate the XML into DOM operations, which is similar to manipulating HTML. However, manipulating the XML to manipulate the DOM without JSON is good, let's look at the following example:
<user> <name>sharpxiajun</name> <city>shanghai</city></user>
If we use the DOM to manipulate the XML to get the value of the name, we have to traverse, the above example is very simple, if the more complex point that there are child elements under the name, then this traversal is deeper, the programming is more complex, but we have an alternative way to look at the following XML:
<user name= "Sharpxiajun" city= "Shanghai" ></user>
At this point we can get the value of name using Xxx.getattribute ("name"), and the XML is simpler than the above and the data is smaller. But this also shows that the XML is too flexible, the same data can be selected in a variety of ways, the result is that the XML performance data is not intuitive, while the volume of data transmission is also very large, and the transmission of the data there is a lot of content is used to express the meaning of the data, rather than really useful data. In contrast, JSON-formatted data is relatively simple, such as the following JSON:
{"Name": "Sharpxiajun", "City": "Shanghai"}
We can understand this JSON very clearly, and JSON is easy to translate into JavaScript objects, so the JSON eventually replaces the XML.
Speaking of JSON, I want to insert a sentence, I remember a netizen once asked me a question, said he did a code review when a young programmer asked him a question, because ask my friend in the implementation of AJAX operations like to use JSON to pass data (this friend generally with jquery), So every time I construct a parameter, he likes to write:
var param = {name: "Sharpxiajun", City: "Shanghai"}
Young programmers think his writing is not standardized, because the JSON specification, whether it is the name of the name of the value or the value of the quotation marks (fortunately, the programmer said the quotation marks, not excluding single quotes), then he thought the above writing will have a security risk, the cause of the hidden trouble is not standardized, but asked my friend said he developed for several years Almost all of it, no problem was found, he asked me, I was also asked to fall.
But I now know the answer, what is JSON? The definition of JSON is a representation of a JavaScript object, which is a data format and JSON is not a variable. So JSON is not actually a JavaScript object, it is a data format defined by the pattern of JavaScript object literals, which can be parsed into a map object by the service-side language. In fact, ask my friends to write a little bit of a problem, this friend's writing is the literal definition of JavaScript objects, JavaScript object name value pairs can be used without quotation marks, if you pass in a parameter is a JavaScript object, the program is not a hidden danger, However, when the network is transmitted, the JavaScript object becomes JSON format, and the browser will enclose the name of the name value pairs in quotation marks.
Detail Six:the core object of Ajax XMLHttpRequest can manipulate the HTTP request header.
For example:
Xhr.setrequestheader ("Content-type", "Application/json; Charset=utf-8; ");
This gives Ajax a lot of flexibility, remember a beginner once asked me a question, XMLHttpRequest can operate HTTP request header, that synchronous request how to define the request header? I was also stuck with this problem, the synchronization request can we operate the request header? I was not able to answer, in fact, the synchronous commit request can change the HTTP request header, which is the META tag of HTML, as shown in:
In contrast, XMLHttpRequest is more flexible in the operation of the request header.
Oh, 11:30, write not finished, had to divide the article, the next article I will continue to explain the Ajax technology, and then the synchronous submission and Ajax technology for comparison, next talk about Comet (server Push technology), and finally a big summary. Maybe I can remember more of it.
Explore Web page Sync submissions, Ajax and Comet Secrets (prev)