【问题标题】:Javascript alert() not showing without const string?Javascript alert() 在没有 const 字符串的情况下不显示?
【发布时间】:2015-03-23 21:17:56
【问题描述】:

我要做的就是在布尔“结果”为假时弹出一个 javascript 警报。

当 'result' 为真时,javascript 警报弹出成功。但是,当它为 false 时,警报根本不会显示。

每个警报的用法的唯一区别是不成功的警报使用字符串变量,而成功的警报使用 CONST 字符串。

是否有关于 javascript 警报的规则只允许警报消息使用 const 字符串?

这是我的代码:

var sql = new SqlClass();
var result = sql.DataInsert(Label1.Text);
if (result == false)
{
    cancelButton_Click(this, e);
    string msg = LotInfo.SubmitError; //this is just a static string
    string script = string.Format("alert('{0}');", msg);
    ScriptManager.RegisterStartupScript(this, typeof(string), "Error", script, true);
}
else
{
    cancelButton_Click(this, e);
    const string msg = "Data successfully submitted!";
    string script = string.Format("alert('{0}');", msg);
    ScriptManager.RegisterStartupScript(this, typeof(string), "Success", script, true);
}

我想补充一点,LotInfo.SubmitError 确实包含一个包含 SqlException 消息的字符串。当我将该字符串存储到 Label.Text 中时,该标签确实会显示在我的页面上。

提前致谢。

编辑: LotInfo.SubmitError 的实际值是一条 SQL 错误消息,所以它真的取决于我得到的错误。

【问题讨论】:

  • 可能是LotInfo.SubmitError中有引号会终止字符串并使生成的javascript不正确。
  • 改用ScriptManager.RegisterStartupScript(this, typeof(string), "InsertError", script, true);。已经有一个名为 Error 的 JavaScript 对象可能与您的脚本冲突
  • 你能告诉我们LotInfo.SubmitError的实际值吗?它是否包含任何撇号?
  • 也作为一种风格注释:你应该尝试用更少的重复行编写你的代码...
  • string script = string.Format("alert('{0}');", msg.Replace("'", "\'"); 试试看

标签: javascript c# asp.net


【解决方案1】:

使用regex 去除任何非字母数字:

Regex r = new Regex("[^a-zA-Z0-9 -]"); //can be adjusted if required
string msg = LotInfo.SubmitError;
string script = string.Format("alert('{0}');",  r.Replace(msg, ""));
ScriptManager.RegisterStartupScript(this, typeof(string), "Error", script, true);

如果您想调整正则表达式条件,请查看此站点 http://www.regexr.com/,它非常适合了解正则表达式语句的作用。

【讨论】:

    【解决方案2】:

    我最终更改了存储在 LotInfo.SubmitError 中的字符串。

    我没有存储 SqlException.Message,而是存储了一个 SqlException.Number 以及一般消息。我相信,正如 mortb 和 JLRishe 所建议的,存储在 SqlException.Message 中的引号、标点符号等正在终止我的 javascript 警报。有一次,我将字符串更改为不包含任何标点符号的消息,弹出警报。

    感谢大家的帮助。

    编辑:Hugo Yates 的回答也是一个解决方案,但我真的不想重新格式化 SQL 错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      相关资源
      最近更新 更多