zoukankan      html  css  js  c++  java
  • Post请求

    写在前面的话:

    XMLHttpRequest对象的open方法的第一个参数为request-type,取值可以为get或post.本篇介绍post请求.

    使用post方式时,浏览器会把各表单中字段元素及其数据作为Http消息的实体内容发送给Web服务器.

    使用post方式时,要注意设置Content-Type的内容为application/x-www-form-urlencoded,设置此内容是为了确保服务器知道实体中有参数变量.

    使用post方式时,参数是随着send方法发送出去的,如send(data).

    使用post方式时,服务器端获取参数时,需要使用Request.Form[data].

    例子

    客户端HTML代码不变,js代码如下:

    function btn_click() {
        //获取参数
        var username = document.getElementById("txt_username").value;
        var age = document.getElementById("txt_age").value;
        //设置字符串参数,并进行编码
        var args = "username=" + encodeURIComponent(username) + "&age=" + encodeURIComponent(age);
    
        //创建XMLHttpRequest对象
        var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    
        //配置连接及方式
        //使用post方式不用担心缓存问题
        xmlHttp.open("post", "post.aspx", true);
    
        //设置Content-Type类型为aapplication/x-www-form-urlencoded,以告知服务器实体中有参数
        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;
            }
        }
    
        //发送参数
        xmlHttp.send(args);
    } 

    服务器端代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
    
        //使用Request.Form来获取数据
        string username = Request.Form["username"];
        int age = int.Parse(Request.Form["age"]);
    
        Response.Write("姓名:'" + username + "'<br/>年龄:" + age + "<br/>时间:'" + DateTime.Now.ToString() + "'");
    
        Response.End();
    }

    现在,我们仍然输入张三,30这两条数据,然后实用工具检查下,看到底发送了什么.

    OverView:

    image

    发送的HTTP Header:

    image

    获取的HTTP Header

    image

    缓存:(此处可以看出,post请求是不会被换缓存的)

    image

    Post的内容:(在get请求时,数据是通过url发送的)

    image 

    小结:

    本片介绍了post是如何使用的.随后的文章,我们会对get请求与post请求做个比较,究竟什么时候适合get请求,什么时候适合post请求呢.

  • 相关阅读:
    前端
    前端
    数据库
    代码块
    装饰器
    函数 初识函数
    相识python --------文件操作
    相识python --------str字符串 int整形 bool布尔值 tu元祖 set()集合 dict 字典的数据补充
    【openstack报错】【因更新包而致】IncompatibleObjectVersion: Version 1.9 of Instance is not supported
    开博第一篇
  • 原文地址:https://www.cnblogs.com/oneword/p/2072593.html
Copyright © 2011-2022 走看看