将javascript变量插入json字符串

Inserting javascript variable into json string

本文关键字:json 字符串 插入 变量 javascript      更新时间:2023-09-26

这应该非常简单,但我总是出错。

我有一个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" />'
   },
});

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

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

考虑到编码风格,我猜您刚刚开始学习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" />'
    }
}

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

调试javascript时,始终检查控制台日志。它们可以帮助准确地找出问题的原因。如果您不知道如何激活控制台,那么在大多数浏览器中,可以使用F12或右键单击->inspect元素来访问控制台。我推荐Google Chrome进行javascript调试。

使用+进行串联
这里也不需要逃避任何事情
您在#之后有一个额外的双引号
您希望在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" />'
    }
});

使用+而不是.来连接字符串。