从JS到PHP的POST请求:错误的JSON

时间:2019-10-03 16:13:01

标签: javascript php ajax post

当我向php发送发布请求时-它向我返回字符串,我对此无能为力。

这是我从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"
};

1 个答案:

答案 0 :(得分:-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);