简体   繁体   English

如何获取ASP.net变量的值到JavaScript文本框中

[英]How to get the value of an ASP.net variable into a javascript textbox

I'm writing some Javascript code for an ASP.net page. 我正在为ASP.net页面编写一些Javascript代码。

I have the string "foo" assigned to a string variable myString . 我已将字符串“ foo”分配给字符串变量myString

I would like to assign the value of myString to a JavaScript variable, so I write in my ASP.net code: 我想将myString的值分配给一个JavaScript变量,所以我用ASP.net代码编写:

<script type='txt/javascript' language='javascript'>
    var stringFromDotNet = '<%=myString%>';
</script>

This works fine as long as myString does not contain quotation marks or line-breaks, but as as soon as I try to assign something with quotation marks or line-breaks, all hell breaks loose and my code doesn't work. 只要myString不包含引号或换行符,此方法就可以正常工作,但是,一旦我尝试分配带引号或换行符的东西,所有地狱便会松散,我的代码将无法正常工作。 As a matter of fact, I can see that this code is vulnerable to all sort of injection attacks. 实际上,我可以看到此代码易受各种注入攻击的攻击。

So... What can I do get the value of myString assigned to a variable in JavaScript? 那么...我该如何获取分配给JavaScript中变量的myString的值?

Update : I've tried creating a page with just an ASP:Hidden field. 更新 :我尝试创建仅包含ASP:Hidden字段的页面。 It looks like the values inside are html encoded. 看起来其中的值是html编码的。

You could use JavaScriptSerializer and that's guaranteed to be safe against XSS: 您可以使用JavaScriptSerializer ,并且保证可以安全地抵御XSS:

<script type="text/javascript">
    var stringFromDotNet = <%= new JavaScriptSerializer().Serialize(myString) %>;
</script>

This approach also allows you to pass complex objects and not just plain strings: 这种方法还允许您传递复杂的对象,而不仅仅是纯字符串:

<script type="text/javascript">
    var complexObjectFromDotNet = <%= new JavaScriptSerializer().Serialize(new { id = 123, name = "foo\"' <bar>" }) %>;
    alert(complexObjectFromDotNet.name);
</script>

I think this may be the answer are looking for: http://www.velocityreviews.com/forums/t70655-escape-function-in-asp-net.html#edit352659 . 我认为这可能是寻找答案的地方: http : //www.velocityreviews.com/forums/t70655-escape-function-in-asp-net.html#edit352659 Basically, encode the value on the server side and unencode it with JavaScript: 基本上,在服务器端对值进行编码,然后使用JavaScript对其取消编码:

var stringFromDotNet = decodeURI(<%=Server.URLEncode(myString)%>);

This will ensure that quotes and other dangerous characters won't break your script, or open up attack vectors. 这将确保引号和其他危险字符不会破坏您的脚本或打开攻击载体。

You could either assign the js variable using double quotes like so 您可以像这样使用双引号分配js变量

var stringFromDotNet = "<%=myString%>";

Or you could escape the single quotes and replace line breaks with literal "\\r\\n" in your string in the server side. 或者,您可以在服务器端的字符串中转义单引号并将换行符替换为文字“ \\ r \\ n”。

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

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