所以我想要做的就是在调用函数时将一个包含 C# 中的错误消息的简单字符串变量传递到我的 javascript 函数中。我的函数调用工作正常,但它不断输出错误的内容。这可能也很重要,我在 Global.asax.cs 文件中调用 Response.Write 片段,而我的 javascript 文件位于 MVC 项目的 Scripts 文件夹中。根据我发现的研究,这是我在评论的帮助下目前得到的:
function KickOutUnwantedUsers(aMesssage) {
console.log("Inside KickOutUnwantedUsers"); //for debugging
console.log(aMesssage); //for debugging
alert(aMessage);
window.open('', '_self').close();
}
它只是继续输出
<%=errorMessage%>
我不确定如何修复它,因为我发现的所有内容都说要以这种方式传递变量,但我想知道是否需要将其作为实际参数传递到函数中,如果是这样,如何做到这一点。
更新:这是 C# 代码:
else
{
string user = s.Remove(0, 4);
string errorMessage = "THE FOLLOWING ERRORS MIGHT HAVE OCCURRED: " + user +
" has either been disabled or the account does not exist." +
" PLEASE CONTACT YOUR ADMINISTRATOR. ";
Response.Write("<script type=\"text/javascript\" src=\"Scripts/HelpfulFunctions.js\">");
Response.Write("</script>");
Response.Write("<script type=\"text/javascript\">");
Response.Write("KickOutUnwantedUsers('" + errorMessage + "');");
Response.Write("</script>");
}
已解决
@Igor 在评论中非常有帮助,我按照他的建议做了事情,由于某种原因一开始行不通,但第二天我删除了我的 JavaScript 文件,用相同的名称重新制作了它并重新输入了 JavaScript 代码,然后有效。编码有时很奇怪。我一定是写错了什么。
最佳答案
这就是(错误记录的)HttpUtility.JavaScriptStringEncode
用于:
// the second argument "true" causes quotation marks to be inserted as well
var message = <%= HttpUtility.JavaScriptStringEncode(errorMessage, true) %>;
关于javascript - 将 C# 中的字符串变量传递给 javascript 函数以在警报框中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43873525/