Ajax 流式传输示例






1.67/5 (2投票s)
2007年11月24日
2分钟阅读

42371

297
一篇关于如何实现 AJAX 的文章
 
 
引言
在我的一个 ASP.NET 1.1 项目中,我必须通过不同的时间间隔的异步 AJAX 调用来更新页面上的两个不同的控件。
作为模拟这种行为的示例,我决定创建一个带有两个标签的网页,标签上显示日期/时间戳。 其中一个标签应每秒更新一次,另一个标签应每 5 秒更新一次。
在我的示例中,我有一个带有两个标签的基础页面,该页面从另外两个页面调用 HTML 数据,以通过异步 AJAX 调用以不同的时间间隔使用当前日期/时间填充标签。
本文试图提供这种方法的一个良好的工作示例。
背景
XmlHttpRequest 是一个对象,您可以使用它通过 JavaScript 向/从服务器发送/获取任何数据。
要实现 AJAX 调用,您实际上需要有两个网页:一个是对最终用户可见的网页,第二个是实际为第一个网页生成所需内容的网页。 第一个页面通过 JavaScript 中实现的 XmpHttpRequest 调用第二个页面。
Using the Code
在下面的示例中,我们将有三个网页
- default.aspx - 将向最终用户显示的页面
- StreamPage1.aspx - 这将为 default.aspx 页面的每秒更新一次的部分提供内容
- StreamPage2.aspx - 这将为 default.aspx 页面的每 5 秒更新一次的部分提供内容。
在提供的示例中,StreamPage1.aspx 和 StreamPage2.aspx 网页是相同的,只有一个标签 - Label1 ,它在 Page_Load 事件上显示当前日期/时间
private void Page_Load(object sender, System.EventArgs e)
{
    Label1.Text=DateTime.Now.ToString();
} 
default.aspx 页面也很简单,只提供了两个部分,分别是带有调用网页名称的文本框、调用 JavaScript 函数 doCall1() 或 doCall2() 的输入按钮,以及<DIV id='panel1'></DIV> 和 <DIV id='panel2'></DIV> 部分,它们实际上将通过 XmlHttpRequest 接受 StreamPage1.aspx 或 StreamPage2.aspx 返回的 HTML。
让我们更详细地考虑项目的主要部分 - AJAX.js。
// Creating the instance of the XmlHttpRequest
// This is done differently for different browsers
// Branch for native XMLHttpRequest object
var client=null;
if (window.XMLHttpRequest)
{
    client = new XMLHttpRequest();
}
// Branch for IE/Windows ActiveX version
else if (window.ActiveXObject)
{
    client = new ActiveXObject("Microsoft.XMLHTTP");
}
//Sending information to server 
function doCall1(datenow)
{
    try
    {
        // Here we provide the URL of the web page that will provide 
        // the content for the main page;
        var url=document.getElementById("txtStreamingPage1").value
        // The parameter ?d= in the next line of code is important
        // Without it the event - onreadystatechange - will never happen
        url=url+'?d='+datenow client.open("GET", url);
        client.onreadystatechange = callBack1;
        client.send();
    }
    catch(ex)
    {
        alert(ex.message);
    }
    // This sets the time interval for 1 second
    setTimeout('doCall1(Date())', 1000);
}
// Waiting and processing server response
function callBack1(response)
{
    try
    {
        if(client.readyState == 4 && client.status == 200)
        {
            document.getElementById("panel1").innerHTML=client.responseText;
        }
    }
    catch(ex)
    {
        alert(ex.message);
    }
}
函数 doCall2() 的工作方式相同,但它是在 5 秒间隔调用的
// This sets the time interval for 5 seconds
setTimeout('doCall2(Date())', 5000); 
关注点
使用上述技术,可以异步更新页面的各个部分,并提供不同的数据。 这在处理应该刷新给用户的数据时非常有用,不仅在用户回发页面时,而是在特定的时间间隔。
