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

标签 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":"输入测试文本","SQLiteManager_currentLangue":"2"}

我希望 json 文件看起来像数字是当前时间(以毫秒为单位)。

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

最佳答案

你几乎需要重做所有事情。我会这样做:

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;

关于javascript - 使用php将ajax发送的数据写入带有数组的json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44055720/

相关文章:

json - 为同一个请求返回不同的 JSON 结果——这是否违反了 REST?

javascript - 单击 div 后将内容推送到 div 的隐藏输入

javascript - 在所有 ajax 调用完成后如何重新加载页面?

php - 使用 JQuery 和 CodeIgniter 将注释安全地写入数据库?

javascript - Symfony2 将变量从 Controller 传递给 javascript

php - 如何在 View 中插入其他模块/ Controller 的输出

json - 如何使用 Blob 存储上的 JSON 作为 Azure 数据工厂的参数?

javascript - 从 Kendo Grid 数据源导出所有数据

javascript - Angularjs ng-Grid注入(inject)错误

java - 有条件地忽略特定属性 DTO