【问题标题】:POST request from JS to PHP: wrong JSON从 JS 到 PHP 的 POST 请求:错误的 JSON
【发布时间】:2019-10-03 16:13:01
【问题描述】:

当我向 php 发送 post 请求时 - 它返回字符串给我,我不能用它做任何事情。

这是我对 JS 的要求:

axios.post("ajax.php", JSON.stringify(myObj))

这就是我在 PHP 中获取数据(来自 JS)的方式:

$data = $_POST;

这就是 $data var_dump 的响应

array(1) {
  ["{"username":"rew","info":"rew"}"]=>
  string(0) ""
}

我需要 2 个变量。第一个用户名和第二个信息。我该怎么做?这条线可以拆分吗?还是我发送格式错误?

我的完整 PHP 代码

$data = array(
  "userName" => $_POST['userName'],
  "pass" => $_POST['pass']
);
$opts = array(
  'http'=>array(
    'method'  => 'POST',
    'content' => json_encode($data),
    'header'  => "Content-Type: application/json\r\n" .
                 "Accept: application/json\r\n" .
                 "Authorization: Basic " . base64_encode("$username:$password"),
  )
);
$context = stream_context_create($opts);
$file = file_get_contents($remote_url, false, $context);
echo $file;

还有 var myObj

let myObj = {
    "username": "rew",
    "info": "rew"
};

【问题讨论】:

标签: javascript php ajax post


【解决方案1】:

看来您不需要stringify 对象。 axios 的默认内容类型将是 application/json,所以这应该可以工作:

axios.post("ajax.php", myObj);

至于$_POST 只会出现内容类型application/x-www-form-urlencodedmultipart/form-data,您需要更改代码以解码原始输入:

json_decode(file_get_contents('php://input'), true);

【讨论】:

  • 我也是这么想的。但在这种情况下,它返回空数组。 json_decode 返回 null。
  • 您能用myObj 示例和您使用的php 代码更新您的问题吗?
  • @AleksKharchenko 你让它太复杂了,不要在这里使用$_POST。还是要求?
  • 使用 'php://input' - 它工作正常,最后我得到正确的 JSON :) 不,这不是必需的,我只是在寻找正确的解决方案
猜你喜欢
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多