How does one pass string contains '\' from from asp.net server side to Javascript function?
How does one pass string开发者_运维问答 contains '\' from from asp.net server side to javascript function?
After checking parameters at client side, all '\' replaced with '' even, replacing '\' with '%5C' at server side doesn't work.
Any idea?
\
is a special character - basically it "escapes" the character after it. Try passing \\
instead. BTW - if you're using C# you can use the @ character before a string to avoid needing to pass it as a double slash, e.g.
string path = @"c:\documents\mydocuments";
I got solution for that.
parameter.Replace("\\", "\\\\")
solve it.
Are you using ASP.NET to write a JavaScript string literal? ie. something like:
Page.RegisterStartupScript("foo",
"<script type='text/javascript'>"+
" var bar= '"+myBarValue+"';"+
"</script>"
);
If so, then you are embedding text inside a delimited JavaScript string literal and you must use an escaping scheme that follows the syntax for string literals. In particular any \
character inside the text must be escaped with \\
, and any '
character must be replaced by \'
, since that's the delimiter being used in this case (JavaScript can use either type of quote to delimit strings).
What's more if you're using an inline <script>
block like in the above example, you're actually embedding text in a string literal in an HTML element, so you have to do some HTML escapes too. In particular you have to break up any </
sequences in the text, because that would end the script block. Also, in XHTML, there are no CDATA elements, so you'd also have to ampersand-escape any <
or &
characters in the text, except that would make it incompatible with legacy-HTML parsers. So to solve all these problems it is better to use JavaScript string literal escapes for that too, replacing <
with \x3C
and &
with \x26
.
Ideally what you would do would be to pass the simple string to a JSON encoder library, which would take care of escaping it appropriately for JavaScript. However I don't know of one for .NET that will escape the HTML for you as above, so you'd still need some replaces.
精彩评论