2012-01-08 47 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