你好,我有一个非常复杂的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语法有问题吗?此外,我以后可以循环所有元素并检索数据吗?提前感谢
您的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.
})
也许只是把[ ... ]
放在JSON周围,这样它就被理解为一个数组,类似于:
var obj = jQuery.parseJSON( '[' + loaded + ']' );
是的,您的JSON语法是错误的。你应该有这样的:
[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]
然后你就会有一个对象数组。