2016-10-15 70 views
1

我想在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輸出

enter image description here

我在做什麼錯?的

+4

當然,你是在爲你的PHP想'json_decode' ... –

+0

我已經嘗試過,但沒有奏效 –

+0

解釋它是如何沒請不要工作。添加您的調試步驟。 –

回答

0

代替

$arrayPHP = (array) json_encode($str_json,TRUE); 

嘗試

$arrayPHP = (array) json_decode($str_json,TRUE); 
+2

你也可以去掉'(array)'cast,因爲這是'true'在第二個參數中所做的。將其轉換爲數組也會阻止您查看是否返回了「null」,這意味着解碼時出現錯誤。 –

+0

我已經嘗試過了,但它不起作用,不幸的是 –

+0

如上面提出的調試,然後發佈錯誤消息,以便我們可以識別可能的錯誤來源 –