2012-05-14 31 views
0

對不起英文:)張貼在json格式

我試圖張貼形式以json格式爲在PHP/python書面restapi。如果我使用json,我無法訪問發佈的數據。見下面

的情況下非JSON的代碼發佈

jQuery(document).ready(function($) { 
    $.post( 
     "http://localhost:8000/api/v1/entry/?format=json", 
     { 
     "body": "This will prbbly be my lst edited post.", 
     "pub_date": "2011-05-22T00:46:38", 
     "slug": "another-post", 
     "title": "Another Post", 
     "username":"admin", 
     "password":"admin" 


     }, 
     function(responseText){ 
      $("#result").html(responseText); 
     }, 
     "html" 
    ); 
    }) 

服務器響應

Array 
(
[body] => This will prbbly be my lst edited post. 
[pub_date] => 2011-05-22T00:46:38 
[slug] => another-post 
[title] => Another Post 
[username] => admin 
[password] => admin 
) 

代碼對JSON後

jQuery(document).ready(function($) { 
    var data = JSON.stringify({ 
    "body": "This will prbbly be my lst edited post.", 
    "pub_date": "2011-05-22T00:46:38", 
    "slug": "another-post", 
    "title": "Another Post", 
"username":"admin", 
"password":"admin" 


}); 

$.post( 
     "testpost.php", 
     data, 
     function(responseText){ 
      $("#result").html(responseText); 
     }, 
     "html" 
    ); 
    }) 

服務器響應

Array 
(
) 

回答

3

那麼,你還沒有分配任何參數的值,因此PHP將無法填充$_POST陣列。

其分配給一個參數,例如json

$.post("testpost.php", {json: data}, ...); 

然後,你將能夠訪問它:

$_POST['json']; 

或者,如果你使用PECL,你可以調用http_get_request_body[docs]到獲取數據。

+0

的eval(數據)會做什麼?或者它會簡單地將json轉換回對象?只是越來越好奇:) – sumit

+0

在PHP或JavaScript?在PHP中,使用'json_decode'並在JavaScript中使用'JSON.parse'。 –

1

這是正常的反應,如果你想獲得張貼DATAS像你這樣的數據必須是鍵值對的數組/對象或正確編碼的查詢字符串的東西很像鍵=值&鍵2 =值... 沒有服務器端,您應該讀取輸入自己類似的東西:

$jsonDatas = file_get_contents('php://input') 

更簡單的方法,你可以在你的JS做:

data = { json: JSON.stringify({...}) } 

,然後得到的結果在$ _ POST [「JSON」]服務器端。

如果你願意,你可以檢查一類礦井,以幫助您JSON服務工作與PHP服務器端的位置:http://projects.jgotti.net/blog/15