简体   繁体   中英

HTTPPost to JSON in PHP

I am doing an HTTP Post request in Javascript in order to update a JSON file.

function updateJson(dataNew){
  var stringData = JSON.stringify(dataNew);
    $.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: 'update.php',
    data: {stringData},
    success : function(d){
       alert('done');}
    })
}

Then in PHP:

<?php
  $a = json_encode(file_get_contents("php://input"));
  file_put_contents('newData.json', $a);
?>

I want JSON data in the JSON file however, the json file only includes a single string which is similar to the request payload of the http post. What am I doing wrong?

I would suggest to pass a key/value pair in the data object, and leave the contentType attribute as default (remove it), like:

$.ajax({
    ...
    data: {myjson: stringData},
    ...
);

Then in PHP you should read the posted data and get that myjson element, without encoding it again, as it is already JSON:

<?php
  $a = $_POST['myjson'];
  file_put_contents('newData.json', $a);        
?>

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