2011-10-13 70 views
1

使用該方法發現here,我收集表格值,並使用下面的代碼張貼:JSON格式

$.ajax({ 
    type: "POST", 
    url: "http://"+document.domain+"/SimplaAdmin/includes/rpc.php", 
    data: { data:postdata, method: 'addSite'}, 
    dataType: "json", 
....... 

發佈的數據是:

data:{ 
    "textfield": ["",""], 
    "dropdown": ["option1","option1"], 
    "siteTitle":"this is the site title", 
    "siteKey":"", 
    "siteurl":"", 
    "address1":"", 
    "address2":"", 
    "address3":"", 
    "landline":"", 
    "method":"addSite", 
    "small-input":"", 
    "medium-input":"", 
    "large-input":"" 
} 

然後我試圖讓價值siteTitle使用:

$data = $_POST['data']; 
$obj=json_decode($data) ; 
$title = $obj->{'siteTitle'}; 

但它不起作用,在哪裏我的想法有缺陷嗎?

+0

嘗試json.stringify - Google-ify it;) – PhD

回答

0

JSON被逸出POST。刪除了斜槓,它的工作。

-1

變化$title = $obj->{'siteTitle'}

$title = $obj['siteTitle']; 
+0

儘管它不是數組。如果你想返回一個數組,你需要用'TRUE'傳遞第二個參數。 – alex

+0

默認情況下,這不起作用'json_decode'返回一個對象。這將導致致命錯誤:不能使用stdClass類型的對象作爲數組錯誤 –

1

你的語法和引線不你只需要$title = $obj->siteTitle;

而且,我相信你添加data:到您的JSON字符串爲這篇文章的目的開始?那也不應該在那裏。

採取例如:

<?php 

$string = '{"textfield":["",""],"dropdown":["option1","option1"],"siteTitle":"this is the site title","siteKey":"","siteurl":"","address1":"","address2":"","address3":"","landline":"","method":"addSite","small-input":"","medium-input":"","large-input":""}'; 

$obj = json_decode($string); 

print_r($obj->siteTitle); 

?> 

其輸出

this is the site title

+0

這將返回null。 data:就是我從Chrome中抓取的內容,顯示發佈的內容,它不在那裏。 – maxum

+0

您是否嘗試過print_r($ obj);看看它是否正確解碼字符串? –

+0

也許嘗試從'data:{data:postdata,method:'addSite'},'看起來像這樣'data:{postdata,method:'addSite'}',' –