2011-12-21 64 views
1

我使用$.getJSON()將一些數據傳遞到服務器端(PHP,Codeigniter)並使用返回數據做一些工作。我發送到服務器的數據是以數組的形式出現的。

問題:當關聯數組發送到服務器時,服務器端沒有收到結果。但是,如果發送帶有數字索引的普通數組,則會在服務器端接收數據。我如何將一組數據發送到服務器?

JS代碼(不工作)

boundary_encoded[0]['testA'] = 'test'; 
boundary_encoded[0]['testB'] = 'test1'; 

$.getJSON('./boundary_encoded_insert_into_db_ajax.php', 
    {boundary_encoded: boundary_encoded}, 
    function(json) { 

     console.log(json); 

}); 

JS代碼(工程)

boundary_encoded[0][0] = 'test0'; 
boundary_encoded[0][1] = 'test1'; 

$.getJSON('./boundary_encoded_insert_into_db_ajax.php', 
    {boundary_encoded: boundary_encoded}, 
    function(json) { 

     console.log(json); 

}); 

PHP代碼

$boundary_encoded = $_GET['boundary_encoded']; 
print_r($_GET); 

錯誤消息

<b>Notice</b>: Undefined index: boundary_encoded in <b>C:\xampp\htdocs\test\boundary\boundary_encoded_insert_into_db_ajax.php</b> on line <b>11</b><br /> 
Array 
(
) 

工作結果

Array 
(
    [boundary_encoded] => Array 
     (
      [0] => Array 
       (
        [0] => test 
        [1] => test1 
       ) 

     ) 

) 
+0

這應該在兩種情況下都起作用。你確定沒有錯字或其他錯誤嗎? – Jon 2011-12-21 14:30:01

+0

我複製粘貼了我實際運行的代碼...我不知道爲什麼它不工作! – Nyxynyx 2011-12-21 14:33:03

+0

是'boundary_encoded [0]'一個數組還是一個對象?如果它是一個數組,則不能執行'boundary_encoded [0] ['testA']',因爲JavaScript不會執行關聯數組。相反,它會爲數組添加一個'.testA'屬性,但它不會被枚舉,這就是爲什麼會發送到服務器的原因。 – Graham 2011-12-21 14:33:11

回答

0

這不起作用的原因是因爲JavaScript不支持關聯數組。這種分配:

boundary_encoded[0]['testA'] = 'test';

出現在JS工作,因爲你可以在新的屬性分配給任何對象,數組包含在內。但是,它們不會在for循環中枚舉。

相反,你必須使用對象文本:

然後可以使用JSON.stringifyboundary_encoded轉換成JSON字符串,發送到服務器,並使用PHP的json_decode()函數將字符串轉換回到對象數組中。

0

我會用轉換陣列JSON建議。如果你不能在PHP這樣做(使用json_encode函數),這裏有幾個JS當量:

+0

我想從客戶端Javascript發送數組到服務器端PHP。我想我需要使用對象字面值而不是Javascript中存在的關聯數組來發送它 – Nyxynyx 2011-12-21 14:49:17

+0

我不確定你的代碼中有多少依賴於數組的使用,但是是的......這將是一個更好的選擇。 – 2011-12-21 14:56:17

0

在你的getJSON調用,使用

{boundary_encoded: JSON.stringify(boundary_encoded)}, 

,而不是

{boundary_encoded: boundary_encoded},