2012-01-08 128 views
0

你好,我有一个非常复杂的PHP脚本,产生一个JavaScript文件在jquery 有一个字符串存储在输入类型的文本,我想转换成json。 输入类型文本具有无限数量的元素。 所以我initisialize在输入框中输入字符串将字符串传递给JSON使用jQuery和循环元素

<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语法有什么问题吗?另外,我稍后能够循环所有元素并检索数据?在此先感谢

回答

2

你的JSON字符串应该是在一个阵列格式像下面

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

然后你就可以通过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. 
}) 
+0

这AINT工作,如果你在JSON格式如[{“按钮”:“BT1”}具有的价值已经我不能创建解析JSON – Theodore 2012-01-08 01:31:32

+0

@Theodore JSON对象,{“按钮” :“BT2”}],你不;吨要做parseJSON(加载),只是加载的变量传递给$。each()并确保在JSON字符串的开始和结尾处有方括号,否则它将无法工作并遍历每个字符而不是每个键。 – 2012-01-08 01:40:48

+0

'var yourJSONstring = [{“button”:“bt1”,“style”:“style1”},{“button”:“bt2”,“style”:“style2”}] $。每个(yourJSONstring,功能(I,价值){ 警报(values.button) 警报(values.style)}' 这段代码不起作用 什么,我做错了什么? – Theodore 2012-01-08 02:31:17

1

也许只是把[ ... ]周围的JSON所以它被理解为一个数组,这样的:

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

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

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

然后你会有你的对象的数组。

+0

不过我越来越一个错误,这是我的字符串在输入类型文本现在: '[{“button”:“small”,“style”:“Link”}]' 另外我hacve试图使用没有jQuery前缀,因为我正在使用它在DOM准备 'VAR OBJ = $ .parseJSON(加载);'但仍没有运气 – Theodore 2012-01-08 01:22:24

+0

你怎么知道这是行不通的?实际上你的代码被执行了吗?从您发布的代码中,我可以看到您的代码将在文档准备就绪时执行,然后您的文本框为空。这是你想要做什么,或者你有一些按钮?你能给我更多的细节吗? – 2012-01-08 01:31:53

+0

我在一些页面上使用了Jquery的其他东西。当我想你的代码,其他的东西打破 这工作得很好,虽然 'VAR OBJ = jQuery.parseJSON(““”“[”。{‘名’:‘约翰’,‘风格’:‘你好’} “:{“HELO”,“世界”}]“”'”);' 注意荫使用字符串concatanation因为我是一个PHP脚本 – Theodore 2012-01-08 01:38:16