JSON格式

时间:2011-10-13 00:14:07

标签: php javascript json

使用找到的here方法,我收集表单值并使用以下代码发布它们:

$.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'};

但它不起作用,我思考的缺陷在哪里?

3 个答案:

答案 0 :(得分:1)

您的语法不正确 - 您只需要$title = $obj->siteTitle;

另外,为了这篇文章的目的,我假设您在JSON字符串的开头添加了data:?那也不应该存在。

以例如:

<?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

答案 1 :(得分:0)

JSON正在逃避POST。删除斜线并且它有效。

答案 2 :(得分:-1)

$title = $obj->{'siteTitle'}更改为

$title = $obj['siteTitle'];