2011-08-09 33 views
0

當從jquery傳遞對象數據到PHP時,我遇到了磚牆。我仍然試圖讓我的頭在OOP。使用和顯示對象數據,PHP和json/jquery

代碼如下:

 <script type ="text/javascript"> 
     $(function() { 


    $(".button").click(function() { 
      //alert("click"); 


      var jsonvar1 = {"skillz": { 
          "web":[ 
            {"name": "html", 
            "years": "5" 
            }, 
            {"name": "css", 
            "years": "3" 
            }], 
          "database":[ 
            {"name": "sql", 
            "years": "7" 
            }] 
     }}; 



      $.ajax({ 
      url: "test2.php", 
      type: 'POST', 
      data: 'regemail=' + jsonvar1, 



       success: function(result) { 
       alert(result); 

       }, 
       error:function (xhr, ajaxOptions, thrownError){ 
       alert(xhr.status); 
       alert(thrownError); 
      } 
      }); 

     }); 
     }); 


     </script> 
    </head> 
    <body> 

<input type="button" id="regSubmit" class="button" value="Register!" /></br></span> 
<script> 
$('input[type=button]').attr('disabled', false); 
    //alert('test'); 
</script> 

上面的代碼做三兩件事。捕獲一個按鈕單擊,然後:eclares變量(jsonvar1),並執行一個PHP的後端該變量的Ajax請求。

現在在PHP後端代碼:

if (filter_has_var(INPUT_POST, "regemail")) { 

    $data = $_REQUEST["regemail"]; 

    //echo "<br>I got some data!</br>"; 

    //print_r($data); 

    //echo $data->skillz; 

    //echo $data; 

    var_dump($data); 

} else { 

echo "No Data."; 
} 

(忽略所有回波,並在上面PHP轉儲這將是我揮舞着約試圖用某種方式的數據)

問:如何將數據從PHP中的對象中抽取到變量或數組中,或者如果您願意,我如何直接使用該對象中的值?(假設它是一個對象,那我不是做其他一些無關的錯誤)

我想知道如果我忘了告訴我的要求,這是JSON ... http://api.jquery.com/jQuery.getJSON/

〜 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 〜 編輯:

我試過添加 echo json_decode($ data); 我的PHP代碼,但它返回一個空白數據集。

我也試圖把 dataType:'json', 在我的ajax查詢。

似乎還沒有任何運氣。

+0

http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests –

+1

你看過PHP json函數(http://www.php.net/manual/en/ref.json.php)嗎?我可能是錯的,但我認爲json_decode正是你正在尋找的。 –

回答

0

你會想在服務器端使用json_encode

if (filter_has_var(INPUT_POST, "regemail")) { 
    $data = $_REQUEST["regemail"]; 

    //echo "<br>I got some data!</br>"; 
    //print_r($data); 
    //echo $data->skillz; 

    echo json_encode($data); 
} else { 
    echo "No Data."; 
} 
+0

hm,這個返回[object Object] – jeremy

+0

我注意到你接受了我的回答,但是你的評論暗示了一個問題。你有沒有遇到別的? – matpie

1

你遇到了一個很簡單的錯誤,很容易忽視:jsonvar1包含的對象,當您連接到「regemail =」與+運營商,它變成一個字符串 - 但不是以你想要的方式。結果字符串是「[object Object]」,因爲JSON轉換不會自動爲您完成。取而代之的是,該行應是

data: 'regemail=' + JSON.stringify(jsonvar1), 

在你的PHP文件,該行

$data = json_decode($data); 

會給你一個目標一起工作,因爲@sirlancelot已經表示。

+0

非常好,謝謝! – jeremy