首先看一下报错的代码:
1. 添加 ajaxpro.2.dll 引用
具体下载地址 http://download.csdn.net/source/258423
2. web.config 中加
<system.web>
<httpHandlers>
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>
</system.web>
3. Default2.aspx.cs 服务器端代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(Default2));
}
[AjaxPro.AjaxMethod]
public string GetServerTimeString()
{
System.Threading.Thread.Sleep(2000);
return DateTime.Now.ToString();
}
}
4. Default2.aspx中的客户端代码
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head id="Head1" runat="server">
- <title>ajaxpro.2.dll 简单应用</title>
- <script language="javascript" type="text/javascript">
- function getServerTime()
- {
- document.getElementById("div1").innerHTML = "请稍后,正在获取时间..";
- document.getElementById("div1").innerHTML =Default2.GetServerTimeString().value;
- }
- function doAutoSubmit(){
- window.setTimeout("doAutoSubmit()",5000);
- getServerTime();
- }
- </script>
- </head>
- <body οnlοad=doAutoSubmit()>
- <form id="form1" runat="server">
- <div>
- <div id="div1">获取服务器端时间</div>
- </div>
- </form>
- </body>
- </html>
以上代码效果已经实现了ajax无刷新更新,但是在第二次执行ajax方法的时候就开始报告错误,ie报“缺少对象”;ff报“this.timeout() 不是一个函数” ie没多不到半个小时就会假死。
检查了一下代码,主要问题第4步客户端代码这里。代码段中的“document.getElementById("div1").innerHTML =Default2.GetServerTimeString().value;” 是直接将后台ajax方法的返回值赋值给了页面变量。
检查后更改第4步客户端代码为:
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head id="Head1" runat="server">
- <title>ajaxpro.2.dll 简单应用</title>
- <script language="javascript" type="text/javascript">
- function ajax_callback(response)
- {
- document.getElementById("div1").innerHTML = response.value;
- }
- function getServerTime()
- {
- document.getElementById("div1").innerHTML = "请稍后,正在获取..";
- Default2.GetServerTimeString(ajax_callback);
- }
- function doAutoSubmit(){
- window.setTimeout("doAutoSubmit()",5000);
- getServerTime();
- }
- </script>
- </head>
- <body οnlοad=doAutoSubmit()>
- <form id="form1" runat="server">
- <div>
- <div id="div1">获取服务器端时间</div>
- </div>
- </form>
- </body>
- </html>
浏览器不在报错,也不会引起ie假死了。根源原因正在学习,明白之后再更新此文。。