簡體   English   中英

從 JS 到 PHP 的 POST 請求:錯誤的 JSON

[英]POST request from JS to PHP: wrong JSON

當我向 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"
};

看來您不需要對 object 進行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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM