2012-08-28 23 views
0

我正在構建一個進程,其中js對象通過ajax(POST和json類型)提交給php文件,而且我通過迭代已提交的內容在PHP中。JS對象 - >從jquery ajax提交JSON - > php迭代

我的目標是這樣的:

var myObject = { 
    "section1":{ 
    "subitem1":"value1", 
    "subitem2":"value2" 
}, 
    "section2":{ 
    "subitem3":"value3", 
    "subitem4":"value4" 
} 
} 

我的AJAX看起來是這樣的:

$.ajax({ 
url:"test.php?section=section2", 
type:"POST", 
dataType:"json", 
success:function(data){ 
// what i do with the response data 
}, 
data:myObject 
}); 

這裏是我的PHP:

$section = $_GET['section']; 
$json = json_decode($_POST[$section], true); 

foreach($json as $key=>$value){ 
    //if this iteration works here, it'll be the happiest point of my day 
} 

現在,在php上面,如果我把這個特定的部分稱爲$ _POST ['section2'],然後迭代就可以工作。所以使用PHP的變量變量似乎是問題,但我不知道....整個$ _POST似乎也作爲一個對象來進來。 JQUERY AJAX是否會自動對我提交的對象執行JSON.stringify?我試過使用stringify,但它沒有工作..我有最新版本的鉻...

此外,我試圖在$ _POST上使用json_decode ...仍然$ _POST [$節]被解釋爲空...

任何幫助,建議,建議非常感謝!

+0

你能的var_dump $ _POST數組,所以我們可以看到它是如何recieving的數據? – Ray

回答

2

這不會給你的想法,字符串化的對象,並把它作爲一個鍵/值的一部分配對,然後從後欄中解碼。

$.ajax({ 
    url:"test.php?section=section2", 
    type:"POST", 
    dataType:"json", 
    success:function(data){ 
    // what i do with the response data 
    }, 
    data:{json:JSON.stringify(myObject)} 
});  
$section = $_GET['section']; 
$json = json_decode($_POST['json']); 
$current_section = $json->{$section}; 

foreach($current_section as $key=>$value){ 
    //if this iteration works here, it'll be the happiest point of my day 
} 
+0

謝謝!我還沒有測試過這個,但這裏的問題,我有: 如果將對象轉換爲json時提交給PHP是這種情況,我不應該使用'JSON.stringify(myObject)'而不是'$ .parseJSON( myObject)'? '$ .parseJSON(myObject)'不用於創建json對象嗎? –

+0

我的另一個問題是迭代通過ajax提交的內容的標準/最佳實踐方式是什麼? 是否將傳入變量(POST或GET)視爲多維數組或對象?我非常感謝你的幫助。 –

+0

@StillQuestioning你說得對,我解決了。進入$ _GET或$ _POST的數據總是字符串或字符串數​​組(如果名稱末尾有'[]',它將成爲數組的一部分),開發人員應該知道該期待什麼,如果他們不他們錯了。閱讀更多http://www.php.net/manual/en/language.variables.external.php – Musa

0

假設$ _POST數組只有一個值 - 對象 - 嘗試這個辦法:

$section = $_GET['section']; 
$tmpArray = json_decode(array_pop($_POST), true); 
$json = $tmpArray[$section];