使用jquery ajax将JSON发布到PHP

The*_*Guy 18 javascript php ajax jquery json

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

我尝试用fireBug检查,我可以看到POST请求被正确发送,当调用php脚本时,他回复Noooooooob给我,似乎设置了任何POST变量.

我想要的只是让我的数组=)

生成的JSON字符串JSON.stringify:

[
   {
      "id":21,
      "children":[
         {
            "id":196
         },
         {
            "id":195
         },
         {
            "id":49
         },
         {
            "id":194
         }
      ]
   },
   {
      "id":29,
      "children":[
         {
            "id":184
         },
         {
            "id":152
         }
      ]
   },
   ...
]
Run Code Online (Sandbox Code Playgroud)

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);
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

save_categories.php

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

mel*_*elc 20

如果您删除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);
    }
  });
});
Run Code Online (Sandbox Code Playgroud)


小智 5

这对我有用,你可以试试这个。JavaScript

$('#save').click(function() { $.ajax({ type: 'POST', contentType: 'application/json', url: 'save_categories.php', dataType: 'json', data: JSON.stringify({'categories': $('.dd').nestable('serialize')}), success: function(msg) { alert(msg); } }); });

您需要在 save_categories.php 上编写以下代码 $_POST 已预先填充表单数据。

要获取 JSON 数据(或任何原始输入),请使用 php://input。

$json = json_decode(file_get_contents("php://input"));
$categories = $json->categories;
Run Code Online (Sandbox Code Playgroud)