简体   繁体   中英

How to retrieve data transfered by ajax to php variable

I send an object to php file via json type successfully and write it to a .txt file as follows:

<script>
var buyInfo = {
  cartID : '123',
  sum : '456',
};

var data = new FormData();
data.append("data", JSON.stringify(buyInfo)); 
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new 
activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', './buy.php', true );
xhr.send(data);
</script>

However, I can not retrieve this data and assign it to a php variable for printing out as follows:

<?php
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fp = fopen('data.txt', 'w');
fwrite($fp, $data);
fclose($fp);

$obj = json_decode($data);
print $obj->{'cartID'}; // cannot print out
}
echo file_get_contents('data.txt'); //can print out
?>

please show me the way. Thanks.

json_decode method return a object, you can access to its attributes as:

$obj = json_decode($data);
print $obj->cartID;

or passing true as second parameter to get a array something like this:

$obj = json_decode($data, true);
print $obj['cartID'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM