开发者

Javascript error: function XXXX() not defined

开发者 https://www.devze.com 2023-01-31 19:12 出处:网络
I added a javascript function in a page <head> <script type=text/javascript> function show_Alert(error)

I added a javascript function in a page

 <head>
    <script type=text/javascript>
        function show_Alert(error)
        {
           alert(error);
         }
    </script>
</head>

and on button click I am doing this

Protected void btn开发者_如何学Go_Click(object o,Eventargs e)
{
    StringBuilder str = new StringBuilder();
    str.AppendLine("show_Alert('XYZ error')");
    ClientScript.RegisterStartupScript(GetType(),"Alert",str.ToString(),true);
}

But it throws JS error show_Alert is not defined :(

Any Idea, what is wrong here??

Thanx


Your script tag is wrong.
Change it to

<script type="text/javascript">

However, I don't think that's the issue.
I suspect that RegisterStartupScript is emitting its <script> block before the one with your function, so that it ends up calling the function before it exists.
Check where each <script> is in the rendered source.


Make sure your <script> element is valid, like this:

<head>
  <script type="text/javascript">
    function show_Alert(error)
    {
      alert(error);
    }
  </script>
</head>

If it's not well formed, or the type is unrecognized (your case has both) then the script inside will be ignored, since the browser doesn't know how to handle it.


Here's an example:

<%@ Page Language="C#" %>
<script type="text/C#" runat="server">
    protected void BtnClick(object sender, EventArgs e)
    {
        var str = "XYZ Error";
        var script = new StringBuilder();
        script.AppendFormat("showAlert('{0}');",
            HttpUtility.JavaScriptStringEncode(str)
        );
        ClientScript.RegisterStartupScript(GetType(), "alert", script.ToString(), true);
    }
</script>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        function showAlert(error) {
            alert(error);
        }    
    </script>
</head>
<body>
    <form id="Form1" runat="server">
        <asp:LinkButton ID="Btn" runat="server" Text="Click me" OnClick="BtnClick" />
    </form>
</body>
</html>

A very important thing to pay attention to is to properly encode the string you are passing to the showAlert function. Notice that it is encoded:

script.AppendFormat("showAlert('{0}');",
    HttpUtility.JavaScriptStringEncode(str)
);

If you don't encode it and the string contains some special characters like ' for instance, your script will break.

0

精彩评论

暂无评论...
验证码 换一张
取 消