【问题标题】:Is it possible to send a json array via post? [closed]是否可以通过 post 发送 json 数组? [关闭]
【发布时间】:2012-10-27 00:44:04
【问题描述】:

我正在尝试将 json 数组发送到 php post 请求。

$myarray[] = 500;
$myarray[] = "hello world";

如何将 $myarray json 数据发送到 php post 请求?

这是我尝试过的:

<form name="input" action="post.php">
<input type="hidden" name="json" value="[500,'hello world']" />
<input type="submit" value="Submit">
</form>

我正在测试 API,并被告知它只需要 json 数据......但我似乎无法让它工作。我的猜测是我错误地发送了 json 数据。有什么想法吗?

【问题讨论】:

  • JSON 对象是文本。是的,您可以通过post 发送短信。
  • @JackManey - Well, actually, 没有 JSON 对象这样的东西。全部都是is a JSON string
  • 如何修改我的代码以发送 JSON 字符串?
  • 如果 API 需要 JSON 编码的请求,那么这些都不起作用。您正在发布一个表单(内容类型 application/x-www-form-urlencoded),其中一个字段是 JSON 编码的,但这可能不是 API 想要的。

标签: php html json post


【解决方案1】:

你遇到的问题是这个字符串不是正确的 JSON:[500,'hello world']

这将是正确的 JSON [500,"hello world"]。 JSON 对格式的要求非常严格,要求所有字符串值都用双引号括起来,绝不能用单引号括起来。

避免问题的正确做法是使用 php 函数 json_encode()json_decode()

例如,

<?php
    $myarray[] = 500;
    $myarray[] = "hello world";
    $myjson = json_encode($myarray);
?>
<form name="input" action="post.php">
    <input type="hidden" name="json" value="<?php echo $myjson ?>" />
    <input type="submit" value="Submit">
</form>

在 post.php 中你会这样读,

<?php
    $posted_data = array();
    if (!empty($_POST['json'])) {
        $posted_data = json_decode($_POST['json'], true);
    }
    print_r($posted_data);
?>

json_decode() 中的 true 标志告诉函数您希望它作为关联数组而不是 PHP 对象,这是它的默认行为。

print_r()函数会输出转换后的JSON数组的php结构:

Array(
    [0] => 500
    [1] => hello world
) 

【讨论】:

  • 好收获。但是,您还需要对 value='..' 属性使用单引号,或者更好地应用 htmlspecialchars(),因此 JSON 双引号不会破坏 HTML 语法。
  • 哎呀,是的,速度有点快,很好地抓住自己。忘记了输入标签 lol 上的引号。如果您想避免特殊字符并避免输入中的单引号,您可以只 base64_encode json,然后在另一端 base64_decode 以避免任何并发症。类似于 facebook 如何在加载 facebook 应用程序时发布他们发布的 json 签名请求。
【解决方案2】:

API 是您的第三方还是您制作的?

如果是你的,那么在你的 API 上使用你的表单发送的数据应该像这样简单:

<?php
    $data = json_decode($_REQUEST['json']);

    echo $data[0]; // Should output 500
    echo $data[1]; // Should output hello world

如果是第 3 方,他们可能希望您在帖子正文中发送 json。为此,请关注此帖子:How to post JSON to PHP with curl

【讨论】:

    猜你喜欢
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多