使用jquery将字符串传递给json并循环元素

时间:2012-01-08 01:07:30

标签: php jquery json

你好,我有一个非常复杂的PHP脚本,在jquery中生成一个javascript文件 有一个字符串存储在输入类型文本中,我想转换为json。 输入类型文本具有未分配的元素数。 所以我在输入框中初始化字符串

<input type="text" id="selectbuttons" value="{}">

在一些操作之后,输入框中的字符串是这样的:

{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}

等...

然后这是我的脚本,我使用函数 addScriptto 将它添加到文档的标题中,我也使用jquery jquery-1.6.2.min.js的核心来制作json对象

$document->addScriptto('
$.noConflict();
jQuery(document).ready(function($) {
var loaded=$("#selectButtons").val();
var obj = jQuery.parseJSON(loaded);
}); //end of dom ready

');

但是当字符串不为空时,我无法使其工作 我的json语法有问题吗?此外,我稍后能够循环所有元素并检索数据?提前致谢

3 个答案:

答案 0 :(得分:2)

您的JSON字符串应采用如下所示的数组格式

[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]

然后您可以使用$ .each循环查看JOSN值,如下所示:

$.each(yourJSONstring,function(i,values) {
  //yourJSONstring holds the JSON array
  // i is just the loop index. it will increment by 1 in every loop
  alert(values.button) //will alert bt1 in the 1st loop, bt2 in 2nd
  alert(values.style) //will alert style1 in 1st loop, style2 in 2nd
  //You can have values here of the keys in JSON using the dot notation as above and do your operations.
})

答案 1 :(得分:1)

可能只是将[ ... ]放在JSON周围,所以它被理解为一个数组,如:

var obj = jQuery.parseJSON( '[' + loaded + ']' );

答案 2 :(得分:1)

是的,您的JSON语法错误。你应该这样:

[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]

然后你将拥有你的对象数组。