我想点击按钮后到后台查询,然后再将查询结果返回给前台界面,前台通过ajax接收。如何做呢?服务器ajax

解决方案 »

  1.   

    需要两个页面,一个是前台,一个是后台处理页面前台
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
            <input id="Button1" type="button" value="button"  onclick="getajax()"/>
        </div>
        </form>
    </body>
    </html>
    <script   type="text/javascript">    //----------------------------------------------------Ajax获取数据--------------------------------------------------------    //传值
        function getajax() {
            document.getElementById('TextBox1').value = getReturn('Server.aspx?id=' + document.getElementById('TextBox1').value);
        }
        //获取页面内容
        function getReturn(Url)  //提交为aspx,aspx页面路径, 返回页面的值
        {
            var xmlhttp;
            try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP") }
            catch (e) {
                try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (E) {
                    //alert("请安装Microsofts XML parsers")
                }
            }        if (!xmlhttp && typeof XMLHttpRequest != "undefined") {
                xmlhttp = new XMLHttpRequest()
            }        try {
                xmlhttp.open('GET', Url, false);
                xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                xmlhttp.send(null);            if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
                    return xmlhttp.responseText;
                }
                else {
                    return null;
                }
            }
            catch (e) {
                alert("你的浏览器不支持XMLHttpRequest对象, 请升级");
            }
            return null;
        }
    </script>后台处理页面(Server.aspx)的ASPX什么都不用处理,在cs页面这样 protected void Page_Load(object sender, EventArgs e)
        {
                Response.Clear();
                //查询数据
              string sql="select value from table where id='"+Request.QueryString["value"].ToString()+"'"
              Response.Write(sql);
        }在前台文本框填写ID后点击按钮就会把拼接好的sql返回,如果想返回查询结果就把查询后的结果输出到页面上,实际上ajax抓取的就是网页源文件
      

  2.   

    你可以使用参数
    如你的ajax 的url可以写
    当前页面aspx?type=ajaxPage_Load里面
    if(Request.QueryString["type"]!=null && Request.QueryString["type"]=="ajax" )
    {
     Response.Clear();
     Response.Write(XXMethod());
     Response.End();
    }private String XXMethod()
    {
     // 执行N多代码,然后返回结果
     return "OK";
    }