一、前言
JavaScript是一种动态的、轻量级的计算机编程语言,而我们在Web后台开发过程中经常会遇到后台方法很难实现而JS却能轻松解决的场景,使用JavaScript的优点如下:
-
更少的服务器交互作用-您可以在将页面发送给服务器之前验证用户输入。这样可以节省服务器流量,这意味着服务器上的负载更少。
-
立即向访问者反馈-他们不必等待页面重新加载就可以查看是否忘记了输入内容。
-
增强的交互性-您可以创建界面,当用户将鼠标悬停在界面上或通过键盘激活界面时会做出反应。
-
丰富的界面-您可以使用JavaScript包含诸如拖放组件和滑块之类的项目,以向网站访问者提供丰富的界面。
二、目录
这里分享几个工作中经常会用到的后台调用JS的方法:
1、自定义弹出信息
2、弹出信息,并跳转指定页面
3、弹出信息,并返回历史页面
4、回到历史页面
5、关闭当前窗口
6、刷新父窗口
7、返回到父窗口
8、页面跳转(跳出框架)
三、具体实现如下
1、自定义弹出信息
public static void Alert(string message)
{
string js = "<script language=javascript>alert('{0}');</script>";
HttpContext.Current.Response.Write(string.Format(js, message));
}
2、弹出信息,并跳转指定页面
public static void AlertAndRedirect(string message, string toURL)
{
string js = "<script language=javascript>alert('{0}');window.location.replace('{1}')</script>";
HttpContext.Current.Response.Write(string.Format(js, message, toURL));
HttpContext.Current.Response.End();
}
3、弹出信息,并返回历史页面
public static void GoHistory(string message, int value)
{
string js = @"<Script language='JavaScript'>alert('{0}');history.go({1});</Script>";
HttpContext.Current.Response.Write(string.Format(js, message, value));
HttpContext.Current.Response.End();
}
4、回到历史页面
public static void GoHistory(int value)
{string js = @"<Script language='JavaScript'> history.go({0}); </Script>";
HttpContext.Current.Response.Write(string.Format(js, value));
}
5、关闭当前窗口
public static void CloseWindow()
{
string js = @"<Script language='JavaScript'>parent.opener=null;window.close();</Script>";
HttpContext.Current.Response.Write(js);
HttpContext.Current.Response.End();
}
6、刷新父窗口
public static void RefreshParent(string url)
{
string js = @"<script>try{top.location=""" + url + @"""}catch(e){location=""" + url + @"""}</script>";
HttpContext.Current.Response.Write(js);
}
7、返回到父窗口
public static void ParentRedirect(string ToUrl)
{
string js = "<script language=javascript>window.top.location.replace('{0}')</script>";
HttpContext.Current.Response.Write(string.Format(js, ToUrl));
}
8、页面跳转(跳出框架)
public static void JavaScriptExitIfream(string url)
{
string js = @"<Script language='JavaScript'> parent.window.location.replace('{0}'); </Script>";
js = string.Format(js, url);
HttpContext.Current.Response.Write(js);
}