【发布时间】:2014-05-05 03:34:40
【问题描述】:
我有一个网页,我公司的人正在使用手机填写。唯一的问题是,如果他们移出信号区,那么当他们尝试更新他们的作品时,页面将转到“未找到页面”,他们将丢失他们已填写的作品。
我正在尝试解决这个问题,目前有这个解决方案:
protected void Button1_Click(object sender, EventArgs e)
{
Session["Online"] = 0;
CheckConnect();
if ((int)Session["Online"] == 1) { Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alertMessage", "alert('You are currently online')", true); }
if ((int)Session["Online"] == 0) { Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alertMessage", "alert('You are currently offline')", true); }
}
protected void CheckConnect()
{
System.Uri Url = new System.Uri("http://www.mypage.com/pixel.jpg?" + DateTime.Now);
System.Net.WebRequest WebReq;
System.Net.WebResponse Resp;
WebReq = System.Net.WebRequest.Create(Url);
try
{
Resp = WebReq.GetResponse();
Resp.Close();
WebReq = null;
Session["Online"] = 1;
}
catch
{
WebReq = null;
Session["Online"] = 0;
}
}
现在,这将检查 www.mypage.com 上的像素文件是否存在(不,这实际上不是我的页面,我已将其替换为此示例),如果存在,则返回 0,如果不是1. 这很好,花花公子。
但是,按下按钮会导致页面重新加载。然后,如果它处于离线状态,它会执行通常的“找不到页面”业务。我的按钮代码在这里:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
基本上,如果我们离线(或者实际上如果我们在线,因为执行更新的代码无论如何都会处理该部分),我希望它不会重新加载页面。
编辑 - 好的,现在不同的方法。使用以下代码完全通过 javascript 执行此操作:
<asp:Button ID="Button1" runat="server" OnClientClick="ifServerOnline()" Text="Button" />
<script type="text/javascript">
function ifServerOnline(ifOnline, ifOffline)
{
var img = document.body.appendChild(document.createElement("img"));
img.onload = function ()
{
ifOnline && ifOnline.constructor == Function && ifOnline();
};
img.onerror = function ()
{
ifOffline && ifOffline.constructor == Function && ifOffline();
};
img.src = "http://www.mypage.com/pixel.jpg?" + Date.now;
}
ifServerOnline(function ()
{
return confirm('Online');
},
function ()
{
return confirm('Offline');
});
</script>
不幸的是仍然导致页面刷新。
【问题讨论】:
标签: c# javascript webforms