gpt4 book ai didi

php - 如何将数组编码为 JSON?

转载 作者:行者123 更新时间:2023-11-29 20:13:59 24 4
gpt4 key购买 nike

我在 JavaScript 中有一个数组,它是 grossIncome。这个数组包含 6 个元素。现在我想使用 $.ajax 方法将此数组发送到另一个 PHP 页面,但我如何才能将此数组编码为 JSON 格式?

最佳答案

使用 JSON.stringify()(如果你想支持旧的浏览器,你必须包含来自 Douglas Crockford 的 this file):

$.ajax(
{
"url": "some_script.php",
"data": {json: JSON.stringify(gossIncome)},
"success": function()
{
// Do something!
}
});

在 PHP 脚本中,您可以使用 json_decode 对其进行解码:

<?php

$json = isset($_GET['json']) ? $_GET['json'] : exit('No JSON passed!');

$array = json_decode($json);

if ( json_last_error() != JSON_ERROR_NONE )
exit('JSON invalid!');

?>

关于php - 如何将数组编码为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8066219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com