简体   繁体   English

PHP中的HTTPPost到JSON

[英]HTTPPost to JSON in PHP

I am doing an HTTP Post request in Javascript in order to update a JSON file. 我正在Javascript中执行HTTP Post请求以更新JSON文件。

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中:

<?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. 我想在JSON文件中使用JSON数据,但是,json文件只包含一个字符串,类似于http帖子的请求有效负载。 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: 我建议在数据对象中传递一个键/值对,并将contentType属性保留为默认值(删除它),如:

$.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中你应该阅读发布的数据并获取myjson元素,而不再重新编码,因为它已经是JSON:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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