[英]Inserting javascript variable into json string
This should be super simple but I keep getting errors. 这应该是非常简单的,但我总是会出错。
I have a JSON string that I need to add a js variable to, the code sample is below. 我有一个需要向其中添加js变量的JSON字符串,代码示例如下。 Essentially I need to add frameVideo variable after the hash tag in the URL string. 本质上,我需要在URL字符串中的hash标签之后添加frameVideo变量。
var frameVideo = window.location.hash.substring(1);
jwplayer("sVid").setup({
'share-video': {
'code': '<embed src="http://www.website.com/test.php#"\'.frameVideo.\'" width="480" height="270" allowfullscreen="true" />'
},
});
What do I need to do differently? 我需要做些什么?
You're using PHP concatenation instead of javascript style. 您使用的是PHP串联而不是javascript样式。
var frameVideo = window.location.hash.substring(1);
var JSON =
{
'code': '<embed src="http://www.website.com/test.php#"' + frameVideo + ' width="480" height="270" allowfullscreen="true" />'
};
Use +
instead of the .
使用+
代替.
to concatenate your string. 连接字符串。
I'm guessing you are just coming over to javascript from PHP, given the coding style. 考虑到编码风格,我猜您只是从PHP转到javascript。 In javascript, we use +
to concatinate, as opposed to the .
在javascript中,我们使用+
代替,而不是.
in PHP. 在PHP中。
JSON strings are essentially javascript objects: JSON字符串本质上是javascript对象:
var obj = {
'share-video': {
'code': '<embed src="http://www.website.com/test.php#' + frameVideo + '" width="480" height="270" allowfullscreen="true" />'
}
}
You are also defining an index of an object outside of the context of an Object. 您还将在对象上下文之外定义对象的索引。 'variable':'something'
is a syntax error when outside of an object. 'variable':'something'
是在对象外部时的语法错误。 Objects are encapsulated within {
and }
. 对象封装在{
和}
。 The above code is semantically correct. 上面的代码在语义上是正确的。
When debugging javascript, always check your console logs. 调试JavaScript时,请始终检查控制台日志。 They can help pinpoint exactly what is causing a problem. 他们可以帮助您准确找出导致问题的原因。 If you didn't know how to activate the console, it is accessed with F12
in most browsers, or by right-click->inspect element. 如果您不知道如何激活控制台,则可以在大多数浏览器中使用F12
或通过右键单击-> inspect元素对其进行访问。 I recommend Google Chrome for javascript debugging. 我建议使用Google Chrome浏览器进行javascript调试。
Use +
for concatenation. 使用+
进行串联。
No need to escape anything here either. 也不用在这里逃脱任何东西。
You have an extra double quote after the #
. #
后面有一个双引号。
You want to use double quotes for key names in JSON (it probably wouldn't make a difference here, but a good habit regardless) 您想对JSON中的键名使用双引号(在这里可能没有什么区别,但是无论如何都是一个好习惯)
You have a trailing comma after your "share-video"
object. 您的"share-video"
对象后面有一个逗号结尾。
var frameVideo = window.location.hash.substring(1);
jwplayer("sVid").setup({
"share-video": {
"code": '<embed src="http://www.website.com/test.php#' + frameVideo + '" width="480" height="270" allowfullscreen="true" />'
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.