javascript - 将带有 jquery ajax 的 JSON 发布到 PHP

标签 javascript php jquery ajax json

我有一个简单的 php 文件,它解码我的 json 字符串,用 ajax 传递,并标记结果,但我不能保留 $_POST 变量,为什么???

我尝试使用 fireBug 检查,我可以看到 POST 请求已正确发送,当调用 php 脚本时,他向我响应 Noooooooob,似乎设置了任何 POST 变量。

我想要的只是拥有我的数组 =)

JSON.stringify 生成的 JSON 字符串:

[
   {
      "id":21,
      "children":[
         {
            "id":196
         },
         {
            "id":195
         },
         {
            "id":49
         },
         {
            "id":194
         }
      ]
   },
   {
      "id":29,
      "children":[
         {
            "id":184
         },
         {
            "id":152
         }
      ]
   },
   ...
]

JavaScript

$('#save').click(function() {
  var tmp = JSON.stringify($('.dd').nestable('serialize'));
  // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
  $.ajax({
    type: 'POST',
    url: 'save_categories.php',
    dataType: 'json',
    data: {'categories': tmp},
    success: function(msg) {
      alert(msg);
    }
  });
});

保存类别.php

<?php
  if(isset($_POST['categories'])) {
    $json = $_POST['categories'];
    var_dump(json_decode($json, true));
  } else {
    echo "Noooooooob";
  }
?>

最佳答案

如果您删除 dataType: 'json',您的代码就可以正常工作,刚刚对其进行了测试。

$('#save').click(function() {
  var tmp = JSON.stringify($('.dd').nestable('serialize'));
  // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
  $.ajax({
    type: 'POST',
    url: 'save_categories.php',
    data: {'categories': tmp},
    success: function(msg) {
      alert(msg);
    }
  });
});

关于javascript - 将带有 jquery ajax 的 JSON 发布到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19976627/

相关文章:

javascript - 将数字更改为数组中的百分比

javascript - Discord.js 机器人在使用命令时崩溃

javascript - pixi.js 中的事件数据

php - 查询失败后,ID 仍在数据库中递增

php - WooCommerce - 在购物车页面上取消设置 "<product> removed notice…"

javascript - jquery动画不显示

javascript - 动态使用 require()

php - 如何在 SQL 查询中使用数组

javascript - 如何让jquery显示和隐藏图像

javascript - IJavaScript 无法正常工作/链接