我想在JavaScript中發送一個JSON字符串,然後用編碼php函數將其轉換爲數組。轉換php數組中的json字符串的問題
一旦使用JavaScript轉換字符串並將Ajax發送到php頁面,我無法將其轉換爲數組。
這就是代碼。
function goJsonAjaxPhp()
{
var myObject ={name:"Andreas",surname:"Grech",age:20};
var str_json = JSON.stringify(myObject);
var xhr;
if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject("Microsoft.HMLHTTP");
}
xhr.onreadystatechange = handler;
xhr.open("POST","page_php.php",true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(str_json);
function handler()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
document.getElementById("idResult").innerHTML= xhr.responseText;
}
}
}
<button onclick=goJsonAjaxPhp()> Json Ajax-PHP </button>
<button onclick=goJsonPhp()> Json Only-PHP </button>
<button onclick=goJsonJavascript()> Json Javascript </button>
<div id=idResult></div>
header("Content-Type: application/json;ì");
$str_json = file_get_contents('php://input');
$arrayPHP = (array) json_encode($str_json,TRUE);
var_dump($arrayPHP);
這是PHP輸出
我在做什麼錯?的
當然,你是在爲你的PHP想'json_decode' ... –
我已經嘗試過,但沒有奏效 –
解釋它是如何沒請不要工作。添加您的調試步驟。 –