ajax - 将数据作为 JSON 发送到 PHP 服务器并接收响应

ajax - sending data as json to php server and receiving response

本文关键字:服务器 PHP 响应 数据 JSON ajax      更新时间:2023-09-26

我试图一次掌握比我应该掌握的更多的东西。

假设我有 2 个输入和一个按钮,在按钮单击时,我想创建一个包含来自这些输入的数据的 json 并将其发送到服务器。

我认为这应该可以做到,但我可能是错的,因为我已经看到了很多不同(解释不佳(的方法来做类似的事情。

    var Item = function(First, Second) {
        return {
            FirstPart : First.val(), 
            SecondPart : Second.val(), 
        };
    };
    $(document).ready(function(){
        $("#send_item").click(function() {
            var form = $("#add_item");
            if (form) {
                item = Item($("#first"), $("#second"));
                $.ajax ({
                    type: "POST",
                    url: "post.php", 
                    data: { 'test' : item },
                    success: function(result) {
                        console.log(result);
                    }
                });
            }
        });
    });

在 PHP 中,我有

class ClientData
{
    public $First;
    public $Second;
    public function __construct($F, $S)
    {
        $this->First = F;
        $this->Second = S;
    }
}
if (isset($_POST['test']))
{
    // do stuff, get an object of type ClientData
}

问题是 $_POST['test'] 似乎是一个数组(如果我把它传递给json_decode我会收到一个错误,说它是一个数组,如果我使用 foreach 迭代它,我会得到我希望看到的值(。那个 ajax 调用正确吗?在 PHP 位中我还应该做点什么吗?

您应该指定 json 的内容类型,并使用 JSON.stringify(( 来格式化数据负载。

$.ajax ({
   type: "POST",
   url: "post.php", 
   data: JSON.stringify({ test: item }),
   contentType: "application/json; charset=utf-8",
   success: function(result) {
      console.log(result);
   }
});

发送 AJAX 请求时,您需要发送有效的 JSON。您可以发送数组,但在将数据发送到服务器之前,您需要形成有效的 JSON。因此,在您的 JavaScript 代码中,表单格式为有效的 JSON,并将该数据发送到您的端点。

在您的情况下,test 键保存一个包含具有两个属性的 JavaScript 对象的value。JSON是字符串格式的键值编码,你的PHP脚本不如何处理JavaScript(jQuery(对象。

https://jsfiddle.net/s1hkkws1/15/

这应该会有所帮助。

发送原始form数据:
JS部分:

$.ajax ({
    type: "POST",
    url: "post.php", 
    data: item ,
    success: function(result) {
        console.log(result);
    }
});

PHP部分:

..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
    $fpart = $_POST['FirstPart'];
    $spart = $_POST['SecondPart'];
    $obj = new ClientData($fpart, $spart);
}
...

要发送json字符串:
JS部分:

$.ajax ({
    type: "POST",
    url: "post.php", 
    data: {'test': JSON.stringify(item)},
    success: function(result) {
        console.log(result);
    }
});

PHP部分:

..
if (isset($_POST['test']))
{
    $json_data = $_POST['test'];
    $json_arr = json_decode($json_data, true);
    $fpart = $json_arr['FirstPart'];
    $spart = $json_arr['SecondPart'];
    $obj = new ClientData($fpart, $spart);
}
...

尝试在 ajax 中发送:

data: { 'test': JSON.stringify(item) },

相反:

data: { 'test' : item },