Differences between Get and Post methods in Ajax

Source: Internet
Author: User
Tags html header


When we access the server using Ajax without reloading the page, we have two options to transfer the request information to the server. The two options are GET and POST.

When sending request information to the server to load a new page, there are two differences between the two options. The first difference is that you requested a small part of the information instead of the entire page. The second and most obvious difference is that Ajax requests do not appear in the address bar, so when sending a request, there is no difference on the visitor's screen. Using GET to generate calls will not expose the domain and their values, nor will POST be exposed. Therefore, how can we choose between them?

A possible mistake for beginners is that most calls use the GET command, just because this command is easier to write. The most significant difference between GET and POST calls is that when a new page loading request is sent, GET calls have the same limit on the same amount of data. The only difference is that you process a small amount of Ajax request data, and you do not want to load the page through this length running limit. Beginners may use POST in a few cases, such as when they do need to transmit more information.

The best way to transfer a large amount of data is to send multiple Ajax calls with only a small amount of information at a time. If you are using an Ajax call to send a large amount of data, it is best to end this approach, because this does not save time.

Therefore, is it possible for us to hesitate between GET and POST to transmit a large amount of data? Both methods are designed for different purposes, and the difference between the two lies in their purpose. This statement applies not only to GET and POST, but also to other methods.

GET is used to obtain information just like its name. It aims to display the information you want to read on the page. The browser caches the execution result of the GET request. If the same GET request is sent again, the browser displays the buffered result instead of re-running the entire request. This process is different from the browser's processing process, but it is intentionally designed to make GET calls more efficient. GET will retrieve the data to be displayed on the page, and the data will not be changed on the server. Therefore, the same results will be obtained when you request the same data again.

The POST method should be used to update the server information. If a call needs to change the data stored 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 POST call, this is because the first call has updated some of the values. A post call usually gets a response from the server rather than keeping the buffer of the previous response.

Therefore, do not use the amount of data to decide whether to select GET or POST, but choose between the two based on the purpose. If you want to retrieve data on the server, use GET. If the value to be retrieved changes with time and update process, you must add a current time parameter to the GET call, in this way, subsequent calls will not use the previously 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 the standard for choosing how to use GET and POST calls, but also use it as the standard to choose between the two calls when processing the page processing form.

Difference between Get and Post

In Ajax, we often use get and post requests. When will get requests and post requests be used? Before answering the questions, we must first understand the difference between get and post.

  1. Get adds the parameter data queue to the URL referred to by the ACTION attribute of the submission form. The values correspond to each field in the form one by one and can be seen in the URL. Post uses the HTTP post mechanism to place fields in the form and their content in the html header and send them to the URL address referred to by the ACTION attribute. You cannot see this process.
  2. For the get method, the server uses Request. QueryString to obtain the value of the variable. For the post method, the server uses Request. Form to obtain the submitted data. You can use Request to obtain parameters in either of the two methods.
  3. The data size transmitted by get is small and cannot exceed 2 kb. The amount of data transmitted by post is large, which is generally not restricted by default. However, in theory, it varies with servers.
  4. Get has low security and high post security.
  5. <Form method = "get" action = "a. asp? B = B "> with <form method =" get "action =". asp "> is the same. That is to say, when the method is get, the parameter list behind the action page is ignored, while <form method =" post "action =". asp? B = B "> unlike <form method =" post "action =" a. asp ">.

In addition, a Get request has the following features: it will add data to a URL and pass the data to the server in this way. Generally, a question mark is used? It indicates the end of the URL address and the beginning of the Data parameter. Each Data parameter in the following parameter appears in the form of "name = value". A connector & is used to distinguish between the parameter and the parameter. Post requests have the following features: data is stored in the HTTP body. They are organized in different ways, including connection and delimiter, which can hide parameters and transmit a large amount of data, convenient.

Through the above instructions, we now have a general idea of when to use get and when to use post, right! When submitting a form, we usually use the post method. When we want to transmit a large data file, we need to use post. When the passed value only needs to be in the parameter mode (this value is not greater than 2 kb), use the get method.

Now let's look at the difference between the get method and the post method when a request is sent through a URL. In the following example, we can easily see the difference between sending the same data through GET and POST. The sent data is username = John.

In GET mode, enter http: // localhost? in the browser? Username = James

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

POST method:

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

The difference is that a form parameter and value are included in a URL request, and a form parameter and value is included in the message entity of an HTTP request.

After comparing the above two paragraphs, we will find that the GET method places the Form Content in the front request header, while the POST method places the content in the Request body, meanwhile, set the request Content-Type header to application/x-www-form-urlencoded in POST. the sent body is the same, so you can construct a form submission body: encodeURIComponent (arg1) = encodeURIComponent (value1) & encodeURIComponent (arg2) = encodeURIComponent (value2) &.....

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

After learning about the above content, we now use the XMLHttpRequest object of ajax to send some data to the server in the GET and POST methods.

GET Method

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

POST method

var postContent ="name=" + encodeURIComponent("xiaocheng") + "&amp;email="
+ encodeURIComponent("xiaochengf_21@yahoo.com.cn");
xmlhttp.open("POST", "somepage", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//Xmlhttp.setrequestheader ("content type", "text / XML"); / / if you are sending an XML file
xmlhttp.send(postContent);
Get Method

The get method is the most common. Generally, the get method is used for user logon and password modification.

Create an html document. The body TAG content is as follows:

<body style="text-align: center">
<input type ="text" id ="txt" />
<br / >
< input type = "button" value = "get method callback" onclick = "get()" / >
</body>

Js Code File

Var XHR = getxhr(); / / get the XMLHttpRequest object. The specific implementation of getxhr function is not given here, because it is very simple
function get()
{
var str=document.getElementById ("txt").value;
Var url = "pageajax. ASPX? Argument =" + escape (STR); / / encode str
xhr.open("get",url,true);
xhr.onreadystatechange=renew;
XHR. Send (null); / / nothing is sent because the URL contains parameter data
}
function renew()
{
if (xhr.readystate==4)
{
if (xhr.status==200)
{
var response=xhr.responsetext;
var res=response.split('\n');
alert(res[0]);
}
}
}

The code for the PageAjax. aspx. cs file on the server side is as follows:

protected void Page_Load(object sender, EventArgs e)
{
if (Request["argument"] != null)
{
String res = "callback in post mode successfully implemented! The parameter passed in is: "+ request [" argument "]. Tostring() +" \ n ";
Response.Write(res);
}
}

This simple get method callback is complete.

Post method

Because parameters such as the user name and password must be input to the url address every time in get mode, the transmission mode can be considered because of the few characters, but when there are many parameters and the string value of the parameter is very long (for example, you cannot pass the content of the entire blog to the url in the form of parameters), this method is not good, because of the post method.

Create an html document. The body TAG content is as follows:

<textarea id="TextArea1" style="width: 323px; height: 76px"></textarea>
<br / >
< input id = "button1" type = "button" value = "post method callback" onclick = "post()" / >

Js Code File

Var XHR = getxhr(); / / get the XMLHttpRequest object. The specific implementation of getxhr function is not given here, because it is very simple
function post()
{
var str=document.getElementById ("TextArea1").value;
var poststr="arg="+str;
Var url = "pageajax. ASPX? Time =" + new date(); / / add a time stamp to place the returned data as the data cached by the server
xhr.open("post",url,true);
XHR. Setrequestheader ("content type", "application / x-www-form-urlencoded"); / / tells the server to send text
//XHR. Setrequestheader ("content type", "text / XML"); / / tells the server to send an XML file
xhr.onreadystatechange=update;
XHR. Send (poststr); / / send poststr data to the server
}
function update()
{
if (xhr.readystate==4)
{
if (xhr.status==200)
{
var response=xhr.responsetext;
var res=response.split('\n');
alert(res[0]);
}
}
}

The code for the PageAjax. aspx. cs file on the server side is as follows:

protected void Page_Load(object sender, EventArgs e)
{
if (Request["arg"] != null)
{
String res = "get callback successfully implemented! The parameter passed in is: "+ request [" Arg "]. Tostring() +" \ n ";
Response.Write(res);
}
}

This simple post method callback is complete.

Difference between Get and Post code writing

...
function createQueryString(){
var firstName = document.getElementById("firstName").value;
var secName = document.getElementById("secName").value;
var querystring="firstName="+firstName+"&amp;secName="+secName;
}
//GET mode
function doRequestUsingGET(){
createXMLHttpRequest();
var queryString = "test.php?";
queryString= queryString + createQueryString()+"&amp;timstamp="+new Date().getTime();
Ajax.onreadystatechange=handleStateChange;
Ajax.open("GET",queryString,true);
Ajax.send(null);
}
//POST mode
function doRequestUsingPOST(){
createXMLHttpRequest();
/*Note the difference between the following code and get mode*/
var url= "test.php?timstamp="+new Date().getTime();
//Post needs to define the string to send
var queryString=createQueryString();
Ajax.open("POST",url,true);
Ajax.onreadystatechange=handleStateChange;
//Post needs to set request header
Ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
//Parameter is not null
Ajax.send(queryString);
}
function handleStateChange(){
if(Ajax.readyState==4){
If (Ajax. Status = = 200) {........} / / success data other data
}
}
... 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.