简体   繁体   English

引用C#变量时如何处理JavaScript中的双引号

[英]How to deal with double quotes in JavaScript when referencing a C# variable

I'm needing to call a JavaScript function that takes in a string variable that could have double quotes in it. 我需要调用一个JavaScript函数,该函数需要一个字符串变量,该字符串变量中可能带有双引号。 Here's how I pass my variable into the JavaScript function: 这是将变量传递到JavaScript函数的方法:

onclick="copyDescription('<%# Eval("Description") %>');"

The problem is the function never fires because it doesn't like the quotes that might be in the 'Description' variable. 问题在于该函数永远不会触发,因为它不喜欢'Description'变量中的引号。

'Description', for example, could be: 例如,“描述”可以是:

VALVE BALL 1" 2000 RP THRD NACE SS BALON LS-10561

If I remove the double quote from the above description, it works great. 如果我从上述说明中删除双引号,则效果很好。 I further tested this out by doing the following, and it worked as expected: 我通过执行以下操作对此进行了进一步测试,并且按预期工作:

        $(document).ready(function () {
        var str = 'VALVE BALL 1" 2000 RP THRD NACE SS BALON LS-10561';
        copyDescription(str);
    });

I tried doing a .replace('"','\\"') and a .replace('"','') via JavaScript, but neither worked. I can remove the quotes by modifying the C# code that gets the value to remove the double quote, and it works. Just not through JavaScript. Any ideas? 我尝试通过JavaScript进行.replace('“','\\”')和.replace('“','')的操作,但均不起作用。我可以通过修改将值获取为的C#代码来删除引号删除双引号就可以了,只是不能通过JavaScript,有什么想法吗?

The problem is that the " is terminating the HTML attribute and cutting off the JS mid-statement. 问题在于"正在终止HTML属性并切断了JS中间语句。

Double quotes must be represented as &quot; 双引号必须表示为&quot; in attribute values delimited by double quotes. 以双引号分隔的属性值中。

使用Microsoft反跨站点脚本库并在字符串上调用函数JavaScriptEncode()

The solution I went with which was the answer to my question was to use: 我所使用的解决方案是使用我的问题的答案:

onclick="copyDescription('<%# Server.HtmlEncode(Eval("Description").ToString()) %>');"

Server.HtmlEncode works how I need it to. Server.HtmlEncode可以满足我的需要。

Thanks everyone for your help and answers! 感谢大家的帮助和解答!

Have that Eval call output JSON instead or plaintext. 将该Eval调用改为输出JSON或纯文本。 That'll take care of any embedded Javascript metacharacters. 它将处理所有嵌入式Javascript元字符。 I don't know how that'd be done in C#, but in PHP it's simply: 我不知道如何在C#中完成,但是在PHP中很简单:

 onclick="copyDescription(<?php echo json_encode(...) ?>);"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM