使用php从ajax发送的数据写入带有数组的json文件

时间:2017-05-18 18:50:32

标签: javascript php json ajax

我从AJAX请求发送一个字符串和一个数组到一个php文件

我的HTML看起来像这样

<form>
  <input class="description" type="text">
  <input type="submit">
</form>

我的js文件看起来像这样

$('form').submit(function(e){

    e.preventDefault();

    var description = $('.description').val();

    var fileNames = ['1.jpg', '2.jpg'];

    var data = {
        description,
        fileNames
    };

    $.ajax({
        url: 'details.php',
        type: 'POST',
        data,
        success: function(data){
            console.log(data)
        }
    });
});

我的php文件看起来像这样

<?php

$str = file_get_contents("test.json");

// // decode JSON
$json = json_decode($str, true);

$decodedJSON =  json_decode($str, true);
var_dump($decodedJSON);

$description = $_REQUEST;

$milliseconds = round(microtime(true) * 1000);

$description->time = $milliseconds;

file_put_contents('test.json', json_encode($description, JSON_PRETTY_PRINT));

?>

这会将json文件设置为

{"description":"test text entered","SQLiteManager_currentLangue":"2"}

我希望json文件看起来像数字是以ms为单位的当前时间。

{
    "1495134004244": {
        "images": [
            "2.JPG"
        ],
        "description": "test"
    }
}

1 个答案:

答案 0 :(得分:1)

你需要重做几乎所有东西。我会这样做:

HTML:

<form>
    <input type="text" name="description">
    <input type="hidden" name="images[]" value="1.jpg">
    <input type="hidden" name="images[]" value="2.jpg">
    <input type="submit">
</form>

JS:

$('form').submit(function(e){
    e.preventDefault();
    $.ajax({
        url: 'details.php',
        type: 'POST',
        data: $(this).serialize(),
        success: function(data){
            console.log(data)
        }
    });
});

PHP:

// get data from request
$newArray = $_REQUEST;

// get json from file
$json = file_get_contents('test.json');

// turn json into array
$masterArr = json_decode($json, true);

// get current time in milliseconds
$milliseconds = round(microtime(true) * 1000);

// use milliseconds as array key and use the new array as its value
$masterArr["$milliseconds"] = $newArray;

// turn array back to json
$json = json_encode($masterArr, JSON_PRETTY_PRINT);

// save json to file
file_put_contents('test.json', $json);

// echo the json so that you can use it in the AJAX call
echo $json;