ajax 无刷新 显示

来源:互联网 发布:html视频播放器源码 编辑:程序博客网 时间:2024/05/01 11:29


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

namespace HTML5
{
    /// <summary>
    /// Summary description for Sum
    /// </summary>
    public class Sum : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            int a = Convert.ToInt32(context.Request.QueryString["num1"]);
            int b = Convert.ToInt32(context.Request.QueryString["num2"]);
            int result = a + b;



            context.Response.Write(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}




<html>
<head>
 <script language=jscript>
 var xmlHttp;
 function createXMLHttpRequest()
 {
    if(window.ActiveXObject)
    {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest)
    {
      xmlHttp = new XMLHttpRequest();
   }
}


function AddNumber()
{
  createXMLHttpRequest();
  var url= "http://localhost/agv/Sum.ashx?num1="+document.getElementById("num1").value+"&num2="+document.getElementById("num2").value;
  xmlHttp.open("GET",url,true);
  xmlHttp.onreadystatechange=ShowResult;
  xmlHttp.send(null);
}


function ShowResult()
 {
    if(xmlHttp.readyState==4)
    {
       if(xmlHttp.status==200)
       {
           document.getElementById("sum").value=xmlHttp.responseText;
       }
   }
}

 
 </script>
 
</head>
<body>
<div style="text-align: center">
        <br />无刷新求和示例<br />
        <br />
        <input id="num1" style="width: 107px" type="text" onkeyup="AddNumber();" value="0"  />
        +<input id="num2" style="width: 95px" type="text"  onkeyup="AddNumber();" value="0"  />
        =<input id="sum" style="width: 97px" type="text" /></div>
        
</body>
</html>



//**************************************************************

protected void Page_Load(object sender, EventArgs e)
{
string strName = HttpContext.Current.Request.QueryString["name"];
string strRes = "服务器返回的响应信息:\r\n" +
"Hello, " + strName + "!";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strRes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}


.ashx 文件用于写web handler的。其实就是带HTML和C#的混合文件。
同样.aspx也可以代替他的,不过在使用.aspx的时候必须得
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();

不然返回的数据出了你需要的数据外,它还把它自身的html码和一起返回了.



 
        
        
        
        
       
0 0
原创粉丝点击