高天乐 welcome you

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

有时候页面希望使用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()处理一下,就还原包涵特殊字符的字符串了。

 

 

posted on 2011-12-04 01:32  高天乐  阅读(965)  评论(0编辑  收藏  举报