On the difference between post and get passing parameters

When we use Ajax to access the server without reloading the page, there are two options to send the request information to the server. The two choices are GET and POST.

There are two differences between the two options when sending the request information to the server to load a new page. The first difference is that you request a small part of the information, not the whole page. The second and most obvious difference is that Ajax requests do not appear in the address bar, so when sending requests, there are no similarities and differences on the visitor's screen. Generating calls using GET does not expose fields and their values, nor does POST. Therefore, how can we choose between the two?

A mistake that beginners may make is to use the GET command for most calls, just because this command is relatively easy to write. The most significant difference between GET and POST calls is that when a request to load a new page is issued, GET calls have the same restrictions on the same amount of data. The only difference is that you handle a small amount of Ajax request data, and you don't want to load the page through this length limit. Beginners may use POST in a few cases, such as when they really need to send more information.

When we have a lot of data to transfer, the best way is to make multiple Ajax calls that pass only a small amount of information at a time. If you're sending a lot of data with an Ajax call, it's best to end this practice because it doesn't save time.

Therefore, the need to transfer a large amount of data can be a reason for us to hesitate between GET and POST? These two methods are designed for different purposes, and the difference between them also lies in their use purpose. This statement applies not only to the use of GET and POST, but also to other methods.

The purpose of GET is to GET information just like its name. It aims to display the information you want to read on the page. The browser will buffer the execution result of the GET request. If the same GET request is issued again, the browser will display the buffered result instead of rerunning the whole request. This process is different from the browser process, but it is deliberately designed to make GET calls more efficient. The GET call will retrieve the data to be displayed in the page, and the data will not be changed on the server, so the same results will be obtained when re requesting the same data.

The POST method should be used where you need to update the server information. If a call wants to change the data saved on the server, the results returned from two identical POST calls may be completely different, because the value of the second POST call is different from that of the first one, because the first call has updated some of the values. POST calls usually get the response from the server instead of keeping the buffer of the previous response.

Therefore, do not use the amount of data to decide whether to choose GET or POST, but choose between the two according to the purpose. If the call is to retrieve data on the server, use GET. If the value to be retrieved changes with time and the update process, add a current time parameter to the GET call so that subsequent calls will not use the previous incorrect buffer. If the call is to send arbitrary data to the server, you can use POST.

In fact, we should not only use this standard as a standard to select how to use GET and POST calls, but also as a standard to choose between these two calls when dealing with page processing forms.

The difference between Get and Post

We often use get and post requests in Ajax. So when to use get requests and when to use post requests? Before answering, we should first understand the difference between get and post.

  1. get is to add the parameter data queue to the URL indicated by the ACTION attribute of the submitted form. The value corresponds to each field in the form one by one, which can be seen in the URL. Post is to place the fields in the form and their contents in the HTML HEADER through the HTTP post mechanism and transfer them to the URL address indicated by the ACTION attribute. The user cannot see this process.
  2. For get mode, the server uses Request.QueryString to obtain the value of the variable. For post mode, the server uses Request.Form to obtain the submitted data. The parameters of both methods can be obtained by Request.
  3. The amount of data transferred by get is small and cannot be greater than 2KB. The amount of data transferred by post is large, which is generally unlimited by default. But in theory, it varies from server to server.
  4. get security is very low and post security is high.
  5. < form method = "get" action = "a.asp? B = B" > is the same as < form method = "get" action = "a.asp" > that is, when the method is get, the parameter list behind the action page will be ignored; The < form method = "post" action = "a.asp? B = B" > is different from the < form method = "post" action = "a.asp" > method.

In addition, the Get request has the following features: it will add data to the URL and pass it to the server in this way, usually using a question mark? It represents the end of the URL address and the beginning of the data parameter. Each data parameter of the following parameters appears in the form of "name = value". A connector & is used to distinguish between parameters. The Post request has the following characteristics: the data is placed in the HTTP body. There are more than one organization modes, including & connection mode and separator mode. It is convenient to hide parameters and transfer a large amount of data.

Through the above description, now we have a general understanding of when to use get and when to use post, right! When we submit a form, we usually use post. When we want to transfer a large data file, we need to use post. When the passed value only needs parameter mode (the value is no more than 2KB), use get mode.

Now let's look at the difference between get and post when sending a request through a URL. Using the following example, you can easily see the difference between sending the same data through get and post. The sent data is username = Zhang San.

GET mode, browser type http://localhost?username= Zhang San

 1 GET /?username=%E5%BC%A0%E4%B8%89 HTTP/1.1
 2 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
 3 Accept-Language: zh-cn
 4 Accept-Encoding: gzip, deflate
 5 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
 6 Host: localhost
 7 Connection: Keep-Alive

POST mode:

 1 POST / HTTP/1.1
 2 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
 3 Accept-Language: zh-cn
 4 Content-Type: application/x-www-form-urlencoded
 5 Accept-Encoding: gzip, deflate
 6 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
 7 Host: localhost
 8 Content-Length: 28
 9 Connection: Keep-Alive
10 username=%E5%BC%A0%E4%B8%89

The difference is that the form parameters and values are attached to the URL request, and the other is in the message entity of the HTTP request.

Comparing the above two paragraphs, we can find that the GET method puts the form contents in the previous request header, while the POST puts these contents in the request body. At the same time, the POST sets the request content type header to application/x-www-form-urlencoded. And the sent body is the same, A form submission body can be constructed as follows: encodeuricomponent (arg1) = encodeuricomponent (value1) & encodeuricomponent (arg2) = encodeuricomponent (Value2) &

Note: encodeURIComponent returns a new String object (Unicode format) containing charstring content. All spaces, punctuation, accents and other non ASCII characters are replaced by% xx encoding, where xx is equal to the hexadecimal number representing the character. For example, a space returns "% 20". Characters with a value greater than 255 are stored in% uxxxx format. See the encodeURIComponent() method of JavaScript

After understanding the above content, we now use the XMLHttpRequest object of ajax to send some data to the server by GET and POST respectively.

1 var postContent ="name=" + encodeURIComponent("xiaocheng") + "&email="
2 + encodeURIComponent("xiaochengf_21@yahoo.com.cn");
3 xmlhttp.open("GET", "somepage" + "?" + postContent, true);
4 xmlhttp.send(null);

POST mode

1 var postContent ="name=" + encodeURIComponent("xiaocheng") + "&email="
2 + encodeURIComponent("xiaochengf_21@yahoo.com.cn");
3 xmlhttp.open("POST", "somepage", true);
4 xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
5 //xmlhttp.setRequestHeader("Content-Type", "text/xml"); //If you are sending an xml file
6 xmlhttp.send(postContent);

get mode

Get is the most common method. Generally, get is used to log in and change the password.

Create a new html document with the body tag as follows:

1 <body style="text-align: center">
2     <input type ="text" id ="txt" />
3     <br />
4     <input type ="button" value ="get Mode callback"  onclick ="get()" />
5 </body>

js code file

 1 var xhr=getXHR();//get xmlhttprequest object,getXHR The specific implementation of the function is not given here because it is very simple
 2 function get()
 3 {
 4     var str=document.getElementById ("txt").value;
 5     var url="PageAjax.aspx?argument="+escape(str);//code str
 6     xhr.open("get",url,true);
 7     xhr.onreadystatechange=renew;
 8     xhr.send(null);//Don't send anything,because url Contains parameter data
 9 }
10 function renew()
11 {
12     if (xhr.readystate==4)
13     {
14         if (xhr.status==200)
15         {
16             var response=xhr.responsetext;
17             var res=response.split('\n');
18             alert(res[0]);
19         }
20     }
21 }  

The server-side PageAjax.aspx.cs file code is as follows

1 protected void Page_Load(object sender, EventArgs e)
2     {
3         if (Request["argument"] != null)
4         {
5             string res ="Successful implementation post Method callback! The parameters passed in are:"+ Request["argument"].ToString()+"\n";
6             Response.Write(res);
7         }
8     }  

Here, a simple get callback is completed.

post mode

Because the get method needs to pass parameters to the url every time, parameters such as user name and password can be passed in this way because there are few characters. However, this method is not good when there are many parameters and the string value of the parameters is very long (for example, blog, you can't pass the content of the whole blog to the url in the form of parameters), Due to the emergence of post mode.

Create a new html document with the body tag as follows:

1 <textarea id="TextArea1" style="width: 323px; height: 76px"></textarea>
2     <br />
3     <input id="Button1" type="button" value="post Mode callback" onclick="post()" />  

js code file

 
 1 var xhr=getXHR();//get xmlhttprequest object,getXHR The specific implementation of the function is not given here because it is very simple
 2 function post() 
 3 {
 4     var str=document.getElementById ("TextArea1").value;
 5     var poststr="arg="+str;
 6     var url="PageAjax.aspx?time="+new Date();//Add a timestamp,The data sent back is the data cached by the server
 7     xhr.open("post",url,true);
 8     xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //Tell the server to send text
 9     //xhr.setRequestHeader("Content-Type", "text/xml"); //Tell the server to send an xml file
10     xhr.onreadystatechange=update;
11     xhr.send(poststr);//send out poststr Data to server
12 }
13 function update()
14 {
15     if (xhr.readystate==4)
16     {
17         if (xhr.status==200)
18         {
19             var response=xhr.responsetext;
20             var res=response.split('\n');
21             alert(res[0]);
22         }
23     }
24 }  

The server-side PageAjax.aspx.cs file code is as follows

 
1 protected void Page_Load(object sender, EventArgs e)
2     {
3         if (Request["arg"] != null)
4         {
5             string res = "Successful implementation get Method callback! The parameters passed in are:" + Request["arg"].ToString() + "\n";
6             Response.Write(res);
7         }
8     }  

Here, a simple post callback is completed.

Differences in coding between Get and Post

 1 .......  
 2 function createQueryString(){  
 3  var firstName = document.getElementById("firstName").value;  
 4  var secName = document.getElementById("secName").value;  
 5   
 6  var querystring="firstName="+firstName+"&secName="+secName;  
 7 }  
 8   
 9   
10 //GET mode  
11 function doRequestUsingGET(){  
12    createXMLHttpRequest();  
13    var queryString = "test.php?";  
14    queryString= queryString + createQueryString()+"&timstamp="+new Date().getTime();  
15    Ajax.onreadystatechange=handleStateChange;  
16    Ajax.open("GET",queryString,true);  
17    Ajax.send(null);  
18   
19 }  
20   
21 //POST mode  
22 function doRequestUsingPOST(){  
23    createXMLHttpRequest();  
24   
25   /* Note the difference between the following code and GET mode */  
26    var url= "test.php?timstamp="+new Date().getTime();  
27    // POST The sent string needs to be defined
28    var queryString=createQueryString();
29    Ajax.open("POST",url,true);  
30    Ajax.onreadystatechange=handleStateChange;  
31    // POST Request header needs to be set
32    Ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded")  
33    // Parameter is not null 
34    Ajax.send(queryString);  
35   
36 }  
37   
38 function handleStateChange(){  
39     if(Ajax.readyState==4){  
40        if(Ajax.status==200){ .......}   //Success data other data  
41     }  
42   
43 }  
44 ......  

 

Tags: Javascript

Posted on Tue, 23 Nov 2021 15:32:10 -0500 by Iceman512