简体   繁体   English

如何在JSON字符串中包含javascript?

[英]how to include javascript in a JSON string?

Ok. 好。 Not sure this is a good idea. 不确定这是个好主意。 I'm building a template which passes a JSON config to a Javascript file assembling the template. 我正在构建一个模板,它将JSON配置传递给组装模板的Javascript文件。

For links I need to include some logic how to build them in my JSON config. 对于链接,我需要包含一些逻辑如何在我的JSON配置中构建它们。 I would have to call this: 我不得不称之为:

path.href.replace( /.*view=/, "" ) + ".cfm?id="+content.vcard.adresses[1]["iln/gln"]

Which in my config JSON: 在我的配置JSON中:

<ul data-template="true" data-config='{  
    "type":"listview",
    "link":"path.href.replace( /.*view=/, '' ) + '.cfm?id='+content.vcard.adresses[1]['iln/gln']",
    "iconpos":"right"
    }'></ul>

Will not work because of quotation-mark-mess, so the JSON is valid, but wrapping it in single quotes messes the HTML up. 因为引号标记混乱而无法工作,因此JSON是有效的,但将其包装在单引号中会使HTML混乱。

Question : 问题
Is there any way to pass this without breaking the HTML? 有没有办法在不破坏HTML的情况下传递这个? Since it's a template I would like to keep the javascript logic as clean as possible = not put in custom methods for every template instance. 由于它是一个模板,我希望尽可能保持javascript逻辑干净=不为每个模板实例添加自定义方法。 So I would like to keep the method call here. 所以我想在这里保持方法调用。

Thanks! 谢谢!

You can escape quotation marks using the &#39; 您可以使用&#39;来转义引号&#39; HTML entity: HTML实体:

<ul data-template="true" data-config='{  
    "type":"listview",
    "link":"path.href.replace( /.*view=/, &#39;&#39; ) + &#39;.cfm?id=&#39;+content.vcard.adresses[1][&#39;iln/gln&#39;]",
    "iconpos":"right"
    }'></ul>

Here is a demonstration: http://jsfiddle.net/fVLPd/ 这是一个演示: http//jsfiddle.net/fVLPd/

Consider using JSON.stringify to build whole JSON string from an object. 考虑使用JSON.stringify从对象构建整个JSON字符串。 Than you don't need to worry about incorrectly encoded quotes or trying to encode quotes in some other way. 您不必担心错误编码的引号或尝试以其他方式编码引号。

If you generate the templates server side - use JSON encoder for your server side language... 如果您生成模板服务器端 - 使用JSON编码器作为服务器端语言...

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

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