加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax--Post请求

发布时间:2020-12-16 00:33:59 所属栏目:百科 来源:网络整理
导读:转自:http://www.cnblogs.com/oneword/archive/2011/06/04/2072593.html 写在前面的话: XMLHttpRequest对象的open方法的第一个参数为request-type,取值可以为get或post.本篇介绍post请求. 使用post方式时,浏览器会把各表单中字段元素及其数据作为Http消息的

转自:http://www.cnblogs.com/oneword/archive/2011/06/04/2072593.html

写在前面的话:

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:

发送的HTTP Header:

获取的HTTP Header

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

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

小结:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读