将 JavaScript 对象传递给 PHP 不起作用


passing JavaScript object to PHP not working

我正在尝试通过JSON.stringify()将我的javascript对象发送到PHP

Javascript:

$('#save').on('click touch', function(){
    obj = {
        "1" : {
            "1" : "hey",
            "2" : "hay"
            },              
        "2" : {
            "1" : "hey",
            "2" : "hay"
            }
    }
    var json = JSON.stringify( obj );
    console.log(json)
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        success: function(data) {
            alert(data);
            $("p").text(data);
        }
    });
});

阿贾克斯.php:

<?php 
    $obj = json_decode($json);
    echo $obj;
?> 

但是此代码返回一个错误,指出未定义$json。我不知道为什么这不起作用。

有 2 个问题。

  1. 您没有随请求发送任何数据
  2. 这不是你在PHP中从请求中获取值的方式。

首先,添加这个*:

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data : { json: json }, // <---------------------
    ...

* 这仅仅是因为 jQuery 实现会自动将任何非字符串数据参数转换为 form-urlencoding 查询字符串。请参阅文档。

然后,在你的PHP中,你应该做:

$jsonStr = $_POST['json'];
$json = json_decode($jsonStr);
<小时 />

编辑:

另一种可能的方法:

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data : json , // <---------------------
    ...

这样,您的数据将不是有效的form-urlencoded输入,因此 PHP 不会将其解析为 $_POST ,但您仍然可以这样做获取输入的内容:

$jsonStr = file_get_contents("php://input");
$json = json_decode($jsonStr);

好吧 - 你永远不会在 AJAX 请求中传递数据!

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: json //<---- RIGHT HERE
    success: function(data) {
        alert(data);
        $("p").text(data);
    }
});

你必须用 ajax 请求发送 obj

 $.ajax({
    type: 'POST',
    url: 'ajax.php',
    data : json,
    dataType : 'json' // for json response
    ...

查看此处的参考 jQuery ajax

数据参数:指定要发送到服务器的数据。

试试这个:

$('#save').on('click touch', function(){
        obj = {
       "1" : {
           "1" : "hey",
           "2" : "hay"
        },              
    "2" : {
        "1" : "hey",
        "2" : "hay"
        }
}
var json = JSON.stringify( obj );
$.ajax({
    data : json,
    type: 'POST',
    url: 'ajax.php',
    success: function(data) {
        alert(data);
        $("p").text(data);
    }
});
});

这个替换你的 ajax 代码。

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: json
    success: function(data) {
        alert(data);
        $("p").text(data);
    }
});

对于 ajax php

<?php 
    $obj = json_decode($_POST['data']);
    echo $obj;
?>