javascript - 为什么 PHP 会忽略 JSON 中的空对象?

标签 javascript php jquery ajax json

我正在尝试使用 post 方法将 JSON 数据从 jQuery ajax 传递到 PHP。然后我必须将此数据保存到文本文件中。

这是我的主对象中的一个 JSON 节点,我想将其提交给 PHP。 我从 Chrome 的控制台捕获了这张图片,因为我很懒。

enter image description here

这是进行调用的 JavaScript 代码:

function save(data, backup, notify, clear) {
  $.ajax({
    type: "POST",
    url: "user.php?action=save&backup="+backup,
    data: data,
    async: false,
      success: function(result){
        console.log(result);
      },
      error:function(e){
          console.log(console.log(e));
      }
  });
}

然后当我尝试在我的 php 中 var_dump 这个 $_POST 数据时,输出如下所示:

var_dump($_POST);
// save
file_put_contents($file, json_encode($_POST,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

enter image description here

正如您所看到的,"file"节点消失了。为什么?如何将空节点传递给 PHP?我只需要带有 key 的"file"节点。一段时间后我会添加一些值。

解决方案:

在 JS 中:

data: {"data": JSON.stringify(data) },

在 PHP 中:

$data = json_decode(stripslashes($_POST['data']));
file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));

最佳答案

问题是你的对象不是 jQuery 认为的 PlainObject

这是一个例子:

var obj = {"c":{}};
var arrayOfObjects = [obj];
jQuery.isPlainObject(arrayOfObjects); // false

看到屏幕开头的[吗?

这是$.ajax data 字段的文档

data Type: PlainObject or String or Array Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

这是 jQuery 关于 traditional setting 的说法。 .

Note: Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead.

您可以通过执行以下操作来解决该问题:

$.ajax({
    type: "POST",
    url: "user.php?action=save&backup="+backup,
    data: JSON.stringify(data),
    // ...
});

据记录,PHP 不存在空 JSON 对象的问题

$json = json_decode('{"c":{},"b":2}');
var_dump(json_encode($json,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
// output
string(33) "{
"c": {

},
"b": 2
}"

关于javascript - 为什么 PHP 会忽略 JSON 中的空对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26958622/

相关文章:

javascript 不是构造函数

javascript - 使用 jquery getJSON 的 Alexa Pagerank

javascript - 如何使用 Sweet Alert 确认提交表单?

php - 在 php 表中显示数据库中的图像

javascript - Jquery 菜单数组在错误的位置打开 ul

javascript - 数字小键盘的 keyCode 值?

javascript - 打开侧边导航时正文中图像的不透明度

javascript - 在同一个 HTML/Angular 页面上有两个时间选择器

JavaScript 按多个(数字)字段对数组进行排序

php - 在 laravel 中具有跨多个 Controller 的通用验证功能