使用 PHP 保存 ajax POST 数据

Saving ajax POST data with PHP

本文关键字:POST 数据 ajax 保存 PHP 使用      更新时间:2023-09-26

我一直在尝试使用ajax和php将一些数据保存到.json文件中。目前我收到错误,我的数据没有被保存,无法找出原因。

这是我.js文件:

var data = {
    "test": "helloworld"
}
    $.ajax({
    url: "save.php",
    data: data,
    dataType: 'json',
    type: 'POST',
    success: function (data) {
        $("#saved").text("Data has been saved.");},
    error: function (data){
        $("#saved").text("Failed to save data !");}
    });

这是我的 php 文件:

    $json = $_POST['data'];
    if(json_decode($json) != null){
      $file = fopen('web/js/data_save.json', 'w+');
      fwrite($file, json_encode($json));
      fclose($file);
    }else{
        print("<pre>Error saving data !</pre>");
    }

当我尝试保存ajax错误时,被触发:

     error: function (data){
 $("#saved").text("Failed to save data !");
     }

我希望有人能引导我朝着正确的方向前进:)

这对我来说很好用

。.js:

 $(document).ready(function() {
    var json_object = {"data": "helloworld"};
    $.ajax({
        url: "../tests/save.php",
        data: json_object,
        dataType: 'json',
        type: 'POST',
        success: function(json_object) {
            console.log(json_object);
            $("#saved").text("Data has been saved.");
        },
        error: function(json_object) {
            console.log(json_object);
            $("#saved").text("Failed to save data !");
        }
    });
});

。.php

$post_data = $_POST['data'];
if (!empty($post_data)) {
    $file = fopen('data_save.json', 'w+');
    fwrite($file, json_encode($post_data));
    fclose($file);
    echo json_encode('success');
} 

如果你对 $_POST 执行var_dump,你会看到你的变量在 PHP 中作为数组发送。 此外,您还需要回显 JSON 字符串以使回调成功

您的请求中没有任何密钥data。您需要使用http_get_request_body或其他东西将整个请求正文解析为 JSON 以获取原始正文,以便获得所需的结果。

编辑:似乎有一些混乱,这里有一些进一步的解释。

向 PHP 发送 JSON POST 请求时,不能像使用普通请求那样使用 $_POST 变量。

curl -H 'Content-Type: application/json' -d '{"foo": "bar"}' myhost/foo.php

使用 FOO.php定义为 波纹管将打印一个空数组,如果需要,请自行尝试。

<?php
print_r($_POST);

当您需要从 POST 请求的正文中获取 JSON 时,您需要获取所有正文,然后从 JSON 中解析它。您可以通过多种方式执行此操作,其中一种是我在编辑之前写的。您还可以通过以下方式获得整个身体而无需使用任何扩展

file_get_contents('php://input')

结果应该是相同的。

因此,使用下面的代码,您应该得到您想要的。

<?php
$json = json_decode(file_get_contents('php://input'), true);
print_r($json);