将javascript变量插入json字符串

时间:2012-07-10 21:48:13

标签: javascript json video jwplayer

这应该非常简单,但我一直都会遇到错误。

我有一个JSON字符串,我需要添加一个js变量,代码示例如下。基本上我需要在URL字符串中的哈希标记之后添加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" />'
   },
});

我需要做些什么不同的事情?

4 个答案:

答案 0 :(得分:0)

您正在使用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" />'
   };

答案 1 :(得分:0)

使用+代替.来连接字符串。

答案 2 :(得分:0)

考虑到编码风格,我猜你只是从PHP转到javascript。在javascript中,我们使用+来连接,而不是PHP中的.

JSON字符串本质上是javascript对象:

var obj = {
    'share-video': {
        'code': '<embed src="http://www.website.com/test.php#' + frameVideo + '" width="480" height="270" allowfullscreen="true" />'
    }
}

您还在Object的上下文之外定义对象的索引。 'variable':'something'在对象外部时是语法错误。对象封装在{}中。上面的代码在语义上是正确的。

调试javascript时,始终检查您的控制台日志。他们可以帮助确切地确定导致问题的原因。如果您不知道如何激活控制台,则在大多数浏览器中使用F12或通过右键单击&gt;检查元素来访问它。我推荐谷歌浏览器进行javascript调试。

答案 3 :(得分:0)

使用+进行连接 也不需要逃避任何事情。
#之后你有一个额外的双引号 你想在JSON中使用双引号作为键名(这可能不会有所不同,但不管是一个好习惯)
您的"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" />'
    }
});
相关问题