2011-10-13 69 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'}',' –