The Difference between Get Request and Post Request in Ajax

Keywords: Windows encoding IIS xml


Written in front

When we use Ajax, when we send data to the server, we can use Get to request the server or Post to request the server. So when should we use Get and when should we use Post?

The difference between Get request and Post request

1. When using Get requests, parameters are displayed in the URL, but not in Post mode.

2. The amount of data sent by Get request is small, while the amount of data sent by Post request is large.

Example

HTML code of the page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        *
        {
            margin:8px;
        }
    </style>
</head>
<body>
    <label for="txt_username">
        Full name:</label>
    <input type="text" id="txt_username" />
    <br />
    <label for="txt_age">
        Age:</label>
    <input type="text" id="txt_age" />
    <br />
    <input type="button" value="GET" id="btn_get" onclick="btn_get_click();" />
    <input type="button" value="POST" id="btn_post" onclick="btn_post_click();" />
    <div id="result">
    </div>
</body>
</html>

Difference:

  Get request Post request
Client foot
//book
//generation
//code
function btn_get_click() {
    var xmlHttp = window.XMLHttpRequest ? 
        new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    var username = document.getElementById("txt_username").value;
    var age = document.getElementById("txt_age").value;

    //Add parameters to avoid caching problems by accessing different URLs each time
    xmlHttp.open("get", "Server.aspx?username=" + encodeURIComponent(username)
        + "&age=" + encodeURIComponent(age) + "&random=" + Math.random());

    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            document.getElementById("result").innerHTML = xmlHttp.responseText;
        }
    }

    //Send the request, parameter null
    xmlHttp.send(null);
}
function btn_post_click() {
    var xmlHttp = window.XMLHttpRequest ?
        new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    var username = document.getElementById("txt_username").value;
    var age = document.getElementById("txt_age").value;
            
    var data = "username=" + encodeURIComponent(username)
        + "&age=" + encodeURIComponent(age);

    //Don't worry about caching
    xmlHttp.open("post", "Server.aspx", true);

    //You must set it, otherwise the server will not receive the parameters.
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            document.getElementById("result").innerHTML = xmlHttp.responseText;
        }
    }

    //Send a request for data data
    xmlHttp.send(data);
}

Difference:

1.get Caching issues should be noted in requests,post Request that you don't have to worry about this problem

2.post Request must be set Content-Type The value is application/x-form-www-urlencoded

3.When sending a request,because get The parameters of the request are all in url in,therefore send The parameters sent by the function are null,and post Request in use send Method Time,But it needs to be given parameters.

For all requests in client code server.aspx,Let's see. server.aspx.cs Code in:

protected void Page_Load(object sender, EventArgs e)
{
    string username = string.Empty;
    int age = 0;

    if (Request.HttpMethod.ToUpper().Equals("GET"))
    {
        username = Request.QueryString["username"];

        age = int.Parse(Request.QueryString["age"]);
    }
    else
    {
        username = Request.Form["username"];

        age = int.Parse(Request.Form["age"]);
    }

    Response.Clear();

    Response.Write("Full name:'" + username + "'<br/>Age:" + age + "<br/>time:'" + DateTime.Now.ToString() + "'");

    Response.End();
}

Here, we find the difference between get requests and post requests on the server side:

When client uses get request, server uses Request.QueryString to get parameters, while client uses post request, server uses Request.Form to get parameters.

With regard to server-side data acquisition, we can also use a common way to obtain parameters, namely Request["username"], but there is a problem with this method, which we will talk about later.

Next, let's use HttpWatch to see what the client sends and receives when sending requests using get and post.

Don't worry about the time difference between get and post requests, because the get and post buttons are pressed at different times.

  OverView
Get request image
Post request image

From the url of the request, it can be seen that the get request has parameters, but the post request url does not.

  Header
Get request
Post request

Because access to the same server, so the information from the server is the same. But the client sent different.

  Header
Get request
Post request

As can be seen from cache, get requests are cached after they are sent, and never cached when post requests are sent.

  Query String
Get request image
Post request image

Because the parameters of the get request are in the url, there is value in the Query String, and no post request.

  POST Data
Get request image
Post request image

In Post Data, because the string requested by get is attached to the url, there is no data in Post Data.

  Content (data obtained from the server)
Get request image
Post request image

The content retrieved from the server is consistent.

    Stream
Get request To the server

GET /AjaxWeb/Article7/Server.aspx?username=%E5%BC%A0%E4%B8%89&age=33&random=0.34838340505348675 HTTP/1.1
Accept: */*
Accept-Language: zh-cn
Referer: http://localhost/AjaxWeb/Article7/Ajax.htm
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET4.0C; .NET4.0E)
Host: localhost
Connection: Keep-Alive

Obtained from the server

HTTP/1.1 200 OK
Date: Sun, 05 Jun 2011 15:36:27 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 60

Pu Zheng:'Lao Zhu Zhu'< br/> Piao Satin: 33 < br/> Piao Degradation:'2011-6-5 23:36:27'

Post request To the server

POST /AjaxWeb/Article7/Server.aspx HTTP/1.1
Accept: */*
Accept-Language: zh-cn
Referer: http://localhost/AjaxWeb/Article7/Ajax.htm
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET4.0C; .NET4.0E)
Host: localhost
Content-Length: 34
Connection: Keep-Alive
Cache-Control: no-cache

username=%E5%BC%A0%E4%B8%89&age=33

Obtained from the server

HTTP/1.1 200 OK
Date: Sun, 05 Jun 2011 15:47:39 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 60

Pu Zheng:'Lao Pao'<br/>Pile satin:33<br/>Degradation:'2011-6-5 23:47:39'

In comparison, the url of get request is parameterized, and the url of post request is parameterized. Post request is not cached.

Now let's consider another question:

As we said just now, when a server accepts parameters, it can adopt a general method, that is, Request["username"] accepts parameters. This way, it can accept parameters sent by get and post requests. So, we do a test to set Content-Type in get requests and send username=zhangsan in send method. Let's see the service. What value does the server return? Modify the server code as follows:

protected void Page_Load(object sender, EventArgs e)
{
    string username = string.Empty;
    int age = 0;

    username = Request["username"];

    age = int.Parse(Request["age"]);

    Response.Clear();

    Response.Write("Full name:'" + username + "'<br/>Age:" + age + "<br/>time:'" + DateTime.Now.ToString() + "'");

    Response.End();
}

In the client, the method of modifying btn_get_click() is as follows:

// Input Zhang San directly as the value of username parameter
 XML Http. open ("get", "Server. aspx? Username="+ encodeURIComponent ("Zhang San")
    + "&age=" + encodeURIComponent(age) + "&random=" + Math.random());

// Add Content-Type information to get request
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

...

// Send the request with username=zhangsan
xmlHttp.send(username = "zhangsan");

Test code, the result output is "Zhang San".

Similarly, next to the above code, let's do another test, modify the post request, and add a username parameter to the url of the open method, with the value zhangsan.

xmlHttp.open("post", "Server.aspx?username=zhangsan", true);

At this point, let's run the project again. What is the result of the server's return? At this time, we find that the result is zhangsan.

When we request get and post, we also put parameters in URL and send method data. Why do we always get parameter values in url?

Answer: When using Request, it traverses Query String, Form, Server Variable and stops searching backwards if it finds data that meets the requirements. So, the username we got in our example is actually the username value in the url.

When to use Get requests and when to use Post requests

The purpose of the Get request is to give the server some parameters to get the list from the server. For example: list.aspx?page=1, which means to get the data on the first page.

The purpose of the Post request is to send some parameters to the server, such as the content in the form.

The following example is used to show the difference between Get request and Post request when sending the same piece of data.

Posted by Arez on Sun, 07 Jul 2019 13:39:47 -0700