php - 通过 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
谢谢!
解决方案
在 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.
阿拉贡
推荐阅读
- php - PHP如何使用preg_match匹配字符串中的精确数字和符号?
- graphql - Shopify StoreFront API GraphQL 查询不返回任何内容
- java - 使按钮功能像键盘
- javascript - 如何在 JSDoc 中评论整个文件?
- arrays - 在处于状态的数组中插入值 - React
- file - 使用进度条提取档案 - 可变借用错误
- javascript - JQuery 自动完成不适用于 materialize.js
- javascript - 使用循环在 JavaScript 中将行与列相乘
- sql - 以所需格式格式化结果集的问题
- javascript - 使用 jQuery 在输入上触发按键