自强不息,止于至善

身无半文,心忧天下;手释万卷,神交古人
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

使用传统的XMLHttpRequest发出Ajax请求

Posted on 2007-11-10 11:15  L.Zhang  阅读(217)  评论(0)    收藏  举报

//客户端脚本

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    
<title>XMLHttpRequest</title>
    
<script language="javascript" type="text/javascript">
        
//根据不同的浏览器,获取XMLHttpRequest对象
        function getXMLHttpRequest()
        {
            
if (window.XMLHttpRequest)
            {
                
return new window.XMLHttpRequest();
            }
            
else
            {
                
var progIDs = [ 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP' ];
        
                
for (var i = 0; i < progIDs.length; i++)
                {
                    
try
                    {
                        
var xmlHttp = new ActiveXObject(progIDs[i]);
                        
return xmlHttp;
                    }
                    
catch (ex) { }
                }
                
                
return null;
            }
        }
        
        
function sendRequest()
        {
            
var xhr = getXMLHttpRequest();
            
//参数为提交方式,和提交地址,是否异步通讯默认为true
            xhr.open("POST""Handlers/RandomNumber.ashx");
            
// xhr.setRequestHeader("header", "value"); 设置头信息
            //设置回调函数
            xhr.onreadystatechange = function()
            {
                onReadyStateChange.apply(xhr);
            }
            
//发送请求
            xhr.send(null);
        }
        
//回调函数
        function onReadyStateChange()
        {   
//判断结果
            if (this.readyState == 4)
            {
                
if (this.status == 200)
                {
                    alert(
this.responseText);
                    
// this.responseXML;
                    // var header = this.getResponseHeader("header"); //获取一个头信息
                    // var headers = this.getAllResponseHeader();     //获取所有头信息
                }
                
else
                {
                    
throw new Error();
                }
            }
        }
    
</script>
</head>
<body>
    
<input type="button" value="Send" onclick="sendRequest()" />
</body>
</html>
//服务器代码RandomNumber.ashx
using System;
using System.Web;

public class RandomNumber : IHttpHandler
{
    
private static Random random = new Random(DateTime.Now.Millisecond);
    
    
public void ProcessRequest (HttpContext context)
    {
        context.Response.ContentType 
= "text/plain";
        context.Response.Write(random.Next());
    }
 
    
public bool IsReusable
    {
        
get
        {
            
return false;
        }
    }

}