如何将HTML区块从背后的代码(C#)传递给javascript函数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何将HTML区块从背后的代码(C#)传递给javascript函数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2614字,纯文字阅读大概需要4分钟。
内容图文
![如何将HTML区块从背后的代码(C#)传递给javascript函数](/upload/InfoBanner/zyjiaocheng/673/8185aa7bda674ae4a0eebafd5a857ae7.jpg)
我目前正在最后一篇论文上.我有一个小问题.我需要将HTML块(它是字符串块)传递给javascript函数.我必须从后面的代码中进行此操作.因为它可以正常工作,下面是代码背后的代码:
string htmlFlightDetailsJavaScript ;
在字符串中,很少有具有类属性的div和表.像div class =“ bla”
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("fill("+htmlFlightDetailsJavaScript+");");
cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true);
这是我的JavaScript函数:
function fill(b)
{
alert(b);
}
请注意,我的JavaScript函数在?.aspx上.
我试图传递不带div和字符串表中的类的字符串,并且可以正常工作.但是当我尝试将其与类一起传递时,它不起作用.有人可以帮我吗?
非常感谢你
解决方法:
听起来好像正在生成无效的Javascript.
可以通过检查传输的实际Javascript并在上下文中验证整个结果的正确性来验证该假设.
也就是说,假设生成了无效的Javascript:
alert("<div class="I just broke JS" ...>")
要解决此问题,请确保插入到Javascript中的字符串文字是有效的.
例如,上面的代码可能(使用以下代码)编写为:
RegisterClientScriptBlock(JsEncoder.Format(@"alert(""{0}"");", theInput))
…并且不会中断,因为字符串之前已转义. (看看这个输出并进行比较:插入的文字将仍然是有效的Javascript,即使theInput中带有引号或其他字符.作为附加的好处,< / script>也可以破坏代码;-)
这段代码是“免费使用,修改,出售,随便”. YMMV.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace sbcjc.sei
{
public class JsEncoder
{
static Regex EncodeLiteralRegex;
// Format a bunch of literals.
public static string Format (string format, params object[] items)
{
return string.Format(format,
items.Select(item => EncodeString("" + item)).ToArray());
}
// Given a string, return a string suitable for safe
// use within a Javascript literal inside a <script> block.
// This approach errs on the side of "ugly" escaping.
public static string EncodeString (string value)
{
if (EncodeLiteralRegex == null) {
// initial accept "space to ~" in ASCII then reject quotes
// and some XML chars (this avoids `</script>`, `<![CDATA[..]]>>`, and XML vs HTML issues)
// "/" is not allowed because it requires an escape in JSON
var accepted = Enumerable.Range(32, 127 - 32)
.Except(new int[] { '"', '\'', '\\', '&', '<', '>', '/' });
// pattern matches everything but accepted
EncodeLiteralRegex = new Regex("[^" +
string.Join("", accepted.Select(c => @"\x" + c.ToString("x2")).ToArray())
+ "]");
}
return EncodeLiteralRegex.Replace(value ?? "", (match) =>
{
var ch = (int)match.Value[0]; // only matches a character at a time
return ch <= 127
? @"\x" + ch.ToString("x2") // not JSON
: @"\u" + ch.ToString("x4");
});
}
}
}
快乐的编码.
内容总结
以上是互联网集市为您收集整理的如何将HTML区块从背后的代码(C#)传递给javascript函数全部内容,希望文章能够帮你解决如何将HTML区块从背后的代码(C#)传递给javascript函数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。