分享一个asp.net使用javascript弹出提示框的方法

有时候页面希望使用javascript的alert弹出一些提示信息,但是信息的格式可能不确定,里面有可能包括",'等,这样在页面解析的时候就会出错,所以我写了一个方法来避免这种错误。

 

public void AlertMessage(Page page, string message)
{
    if (!page.ClientScript.IsStartupScriptRegistered("AlertMessage"))
        page.ClientScript.RegisterStartupScript(page.GetType(), "AlertMessage",
            string.Format(@"<script type='text/javascript'>alert('{0}');</script>", message.Replace("\'""\\'")));
}
调用的时候:
string msg = @"nihao""abda"",'dfas'";
AlertMessage(this.Page, msg);

这样就不会出错了  :)

再稍微解释一下javascript中的escape函数的作用,

<script type="text/javascript">
    document.write(escape("Visit W3School!"));
    document.write("<br />");
    document.write(escape("?!=()#%&"));
    document.write("<br />");
    document.write('Visit W3School!');
    document.write("<br />");
    document.write('?!=()#%&');
    document.write("<br />");
</script>

 这段代码执行之后的结果是

Visit%20W3School%21
%3F%21%3D%28%29%23%25%26
Visit W3School!
?!=()#%&

 所以escape()一般都是配合通过url传递参数的时候使用的,在接受参数的时候使用unescape()处理一下,就还原包涵特殊字符的字符串了。

原文地址:https://www.cnblogs.com/gaotianle/p/2275198.html