使用Javascript从HTML输入字段中提取JSON变量

时间:2014-08-09 15:54:33

标签: javascript php jquery json

我有以下输入HTML元素,我已将json编码的php变量作为值传递。在源代码中它呈现如下:

<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{"name":[{"id":215,"fbid":"19538277626","stage_name":"311","city":"","state":"","image_path":"http:\/\/graph.facebook.com\/19538277626\/picture?width=720&height=720",
"description":"311 was formed in 1990 in Omaha, Nebraska."},{"id":18,"fbid":"14591271531","stage_name":"Beck","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/14591271531\/picture?width=720&height=720",
"description":""},{"id":47,"fbid":"137029526330648","stage_name":"Disclosure","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/137029526330648\/picture?width=720&height=720","description":""},
{"id":11,"fbid":"152513780224","stage_name":"Arcade Fire","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/152513780224\/picture?width=720&height=720","description":""}]}">

我想用javascript,json_decode获取值,然后在JS中将其用作数组。像这样:

var artist_likes = $('#js-helper-artist-likes').val();
console.log(artist_likes);
var artist_likes_decoded = $.parseJSON(artist_likes);
console.log(artist_likes_decoded);

但是,当我打印artist_likes时,它只会出现:

"{"

在控制台中。

我知道这是因为JSON包含打破解析的引号,但有没有办法用javascript拉取文字值?谢谢您的帮助。

4 个答案:

答案 0 :(得分:1)

我认为错误是因为未转义的引号:

value="{"name":
--------^

这里的引用不会被转义。不应该是:

value="{\"name\":

这可能是原因,它过早地被削减,并将输出显示为{。或者处理此问题的最佳方法是使用单引号:

value='{"name":

值得注意的是,JSON值应该是双引号而不是单引号。因此,请确保使用HTML中的单引号和JSON值中的双引号,并转义在JSON值中找到的单引号。

可能的 PHP代码将是:

value='<?php echo str_replace("'", "\\'", $jsonStuff); ?>'

答案 1 :(得分:0)

你需要转义引号,一个简单的方法就是使用撇号:

<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value='{"quotation mark value"}' >

然而,如果你不能保证只使用引号,这不是完全证明,更好的方法是使用反斜杠转义每个单引号,内部值,如下所示:

<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{\"quotation mark value\"}" >

答案 2 :(得分:0)

您好我为您创建了jsfiddle

代码: -

$(document).ready(function() {
    var data = JSON.parse($('#js-helper-artist-likes').val());
    console.log(data);
});

更新代码: - value ='{“name”// - 在启动时使用'代码而不是

工作示例: - http://jsfiddle.net/XUjAH/1104/

答案 3 :(得分:0)

如果您可以在该HTML输入值中获取该JSONEncode值。然后,我认为将编码值分配给JavaScript定义的变量是更好的做法:

<script type="text/javascript">
var artist_likes = <?= json_endoe($phpVariable) ?>;
console.log(artist_likes);
</script>