[英]json_decode after JSON stringify not working properly
我有一個json編碼並發布到PHP的javascript數組。 當我在發布即console.log(selection[878][2824])
之前檢查數組中的值時,我得到了一個值作為結果。 然后使用JSON.stringify
對變量進行json編碼並將其發布到服務器。 但是當我對php中的值進行json_decode
並打印相同時,我得到的是空數組
js腳本
console.log(selection);
$http({
method: 'POST',
url: 'example.php',
data: 'selection='+JSON.stringify(selection),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
PHP腳本
$selectionData = json_decode($_POST['selection']);
print_r($selectionData[878][2824]);
所以在這里編碼數據時發生了什么。 它是怎么丟失的?
似乎數據格式不正確,我認為您必須格式化字符串
"selection :" +JSON.stringify(selection);
嘗試這個
js
$http({
method: 'POST',
url: 'example.php',
data: {selection : JSON.stringify(selection)}
})
的PHP
$data = json_decode(file_get_contents("php://input"),true);
$selection = json_decode($data['selection'],true);
使用POST時不必對內容進行字符串化,只需設置正確的標題即可。
$http({
method: 'POST',
url: 'example.php',
data: selection,
headers: {'Content-Type': 'application/json'}
})
或者如果您需要帶有標識符的代碼:
$http({
method: 'POST',
url: 'example.php',
data: {"selection": selection },
headers: {'Content-Type': 'application/json'}
})
並且在PHP中(如果您使用的是其他標識符):
$selectionData = $_POST['selection'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.