首页 > 解决方案 > 通过 ajax 从 jquery 到 PHP 的 JSON 数组

问题描述

我试图通过 ajax 将 JSON 数组从 jquery 传递到 php,但我无法弄清楚从 php 中的 json 获取特定对象

我的代码:

client side:
var items = [];

items.push({
        name: "Test1",
        ID: "34",
        price: "678"
});

items.push({
    name: "Test2",
    ID: "34",
    price: "678"
});

$.ajax({
        url: "http://localhost/SendObjects.php",
        type: "POST",
        data: JSON.stringify(items),
        success: function (data) {
            var suc = data;
            $('#body').append(suc);
        }
});

PHP:

$_POST = file_get_contents('php://input');
echo $_POST

谢谢!

标签: phpajax

解决方案


在 PHP 中使用来自 JSON 的数据 首先,要深入了解 JSON 只是一个字符串,我们将把 JSON 写入 PHP 字符串并将其应用于名为$data的变量。

$data = '{
    "name": "Aragorn",
    "race": "Human"
}';

然后我们将使用 json_decode() 函数将 JSON 字符串转换为 PHP 对象。

$character = json_decode($data);

现在我们可以将它作为一个 PHP 对象来访问。

echo $character->name;
Here’s the whole file.

<?php

$data = '{
    "name": "Aragorn",
    "race": "Human"
}';

    $character = json_decode($data);
    echo $character->name;
Here is the output.

阿拉贡


推荐阅读