ajax xmlhttprequest使用post传参数并向后台获取数据

         ajax xmlhttprequest向后台传数据有两种方式,一种是直接在地址URL后面加入参数,后台用Request.QueryString来获取,另外一种是采用POST来传,send方法发送参数对,比如send("a=3&b=4"),后台用Request.Form[“a”]来获取3,同理Request.Form["b"]获取4

 

前台代码:

<%@ Page Title="主页" Language="C#"  AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="ajax测试二._Default" %>

<html>
<head>
<script type="text/javascript">
    function getHttpObj() {
        var httpobj = null;
        try {
            httpobj = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                httpobj = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e1) {
                httpobj = new XMLHttpRequest();
            }
        }
        return httpobj;
    }

    function cs() {
        var obj = getHttpObj();
        var sel1 = document.getElementById('cs1');
        //obj.open("get", "default.aspx?id=" + cs1.value, true); //记得小写,亲,并且default.aspx不区分大小写,这里在IE存在缓存问题,使用下面的可以解决
        obj.open("post", "default.aspx?id=" + cs1.value,true);//ajax异步在使用GET方式的时候在IE下面存在缓存,不会向后台请求,不过POST不存在缓存问题
        //obj.send(); //记得小写,亲,不传参数可以直接这样写
        obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");//不加上这句,那么后台Request.Form获取不到参数a,b的数值
        obj.send("a=3&b=4");
        obj.onreadystatechange = function () {//此处为回调函数
            if (obj.readyState == 4 && obj.status == 200) {
                alert(obj.responseText);
            }
        };
    }
</script>
</head>
<body>
<select id="cs1" οnchange="cs();">
<option value="1">江西省</option>
<option value="2">福建省</option>
</select>

</body>
</html>

 

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ajax测试二
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] != null)
            {
                string id = Request.QueryString["id"];
                Response.Write("id:"+Request.QueryString["id"]+",a:"+Request.Form["a"]+",b:"+Request.Form["b"]);
                Response.End();
            }
        }
    }
}

 

 

程序在IE8,filefox,chorme下测试通过

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值