Read associative array from json in $_POST

你。 提交于 2019-11-27 04:21:08

问题


I am using jQuery to post a json object to my php application.

jQuery.post("save.php",JSON.stringify(dataToSend), function(data){ alert(data); });

The json string as pulled from firebug looks like this

{ "data" : [ { "contents" : "This is some content",
        "selector" : "DIV.subhead"
      },
      { "contents" : "some other content",
        "selector" : "LI:nth-child(1) A"
      }
    ],
  "page" : "about_us.php"
}

In php I am trying to turn this into an associative array.

My php code so far is

<?php
$value = json_decode(stripcslashes($_POST));
echo $value['page'];
?>

The response to the ajax call should be "about_us.php" but it comes back blank.


回答1:


You can avoid to use JSON.stringify and json_decode:

jQuery.post("save.php", dataToSend, function(data){ alert(data); });

And:

<?php
echo $_POST['page'];
?>

Update:

... but if your really want to use them, then:

jQuery.post("save.php",  {json: JSON.stringify(dataToSend)}, function(data){ alert(data); });

And:

<?php
$value = json_decode($_POST['json']);
echo $value->page;
?>



回答2:


$_POST will not be populated if the request body is not in the standard urlencoded form.

Instead, read from the read-only php://input stream like this to get the raw request body:

$value = json_decode(file_get_contents('php://input'));



回答3:


Pass the second argument as true if you want the associative array otherwise it will keep returning object.

$value = json_decode(stripslashes($_POST),true);



回答4:


Try:

echo $value->page;

since json_decode's default behaviour is to return an object of type stdClass.

Alternatively, set the second optional $assoc argument to true:

$value = json_decode(stripslashes($_POST), true);
echo $value['page'];



回答5:


It looks like jQuery might encode a javascript object in urlencoded form then would be populated into $_POST. At least from their examples. I'd try passing in your object into post() without stringifying it.




回答6:


If you want to use json data as an associative array, you can try as following:

<?php 

$json = 'json_data'; // json data

$obj = jsondecode($json, true); // decode json as associative array 

// now you can use different values as 
echo $obj['json_string']; // will print page value as 'about_us.php' 


for example: 

$json = { "data" : [ { "contents" : "This is some content",
    "selector" : "DIV.subhead"
   },
   { "contents" : "some other content",
    "selector" : "LI:nth-child(1) A"
   }
  ],
"page" : "about_us.php"
}

$obj = json_decode($json, true); 

/* now to print contents from data */

echo $obj['data']['contents']; 
 // thats all 
?>


来源:https://stackoverflow.com/questions/5806971/read-associative-array-from-json-in-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!