xmlhttprequest同步获取后台数据(一)

本文介绍了一种使用XMLHttpRequest同步获取后台数据的方法,通过JavaScript函数getXmlHttpObject创建请求对象,并在onchange事件中触发函数cs发送GET请求。代码在IE8、Firefox和Chrome下测试通过。示例展示了如何根据选择的下拉框选项获取不同响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.前台代码:

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

<html>
<head>
<script type="text/javascript">
    function getXmlHttpObject() {
        var httpobj = null;
        try{
            httpobj = new ActiveXObject("Microsoft.XMLHTTP");//支持IE
        }
        catch(e) {
            try {
                httpobj = new XMLHttpRequest();//非IE内核的都支持,高版本的IE其实也支持这个了,测试IE8支持

            }
            catch (e) {
                httpobj = new ActiveXObject("Msxml2.XMLHTTP");//支持IE
            }

        }
        return httpobj;
    }

    function cs() {
        var obj = document.getElementById('cs1');
        var index = obj.selectedIndex;
        if (index >= 0) {
            var httpobj = getXmlHttpObject();
            if (httpobj) {
                httpobj.open("GET", "Default.aspx?id="+index, false);//注意此处GET可以大写或者小写,还有一个是此处必须是小写的open,IE是无所谓,但是其它浏览器不支持大写

                //Open
                httpobj.send();   //此处也必须是小写,IE支持Send,但是其它浏览器不支持Send()
                if (httpobj.readyState ==4 && httpobj.status == 200) {
                    alert(httpobj.responseText);
                }
            }
        }
    }
</script>
</head>
<body>
<form id="form1" runat="server" >
<select id="cs1" onchange="cs();" >
    <option value="1" >江西省</option>
    <option value="2">福建省</option>
</select>
</form>
</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测试1
{
    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"];
                if (id == "1")
                    Response.Write("11aa");
                else
                    Response.Write("22aa");
                Response.End();  //这句也必须加上,不然网页源代码都会输出去了,汗
            }


        }
    }
}

 

以上程序经过IE8,Firefox,chrome测试可以正常运行。这里获取的后台数据很简单,只是提供了一个同步获取数据的方式,大家可以举一反三。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值