2014-01-09 140 views
0

我需要從PHP獲取一些JSON數據和AJAX功能 這就是我迄今爲止所寫的內容,但並不確定在PHP端要做什麼。 JS:從AJAX POST獲取JSON數據發送

window.onload = function() { 
    var json = { 
     hello : 'howareyou', 
     good : 'yes i am good', 
     toast : 'i love toast' 
    } 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
     if(xhr.readyState == 4 && xhr.status == 200) { 
      alert(xhr.responseText); 
     } else { 
      alert("no"); 
     } 
    } 
    xhr.open('POST', 'json.php', true); 
    xhr.send(json); 
} 

PHP:

<?php 
if(isset($_POST['json'])){ 
    $json = $_POST ['json']; 
    $json_d = json_decode($json); 
    echo $json . 'hello'; 
} else { 
    echo 'error'; 
} 
?> 

HTML:

<html> 
<head> 
    <script type="text/javascript" src='ajax.js'></script> 
<body> 
HELLO THERE THIS IS AN HTML PAGEEEEE 
</body> 
</html> 
+0

您未發送JSON。您正在將JavaScript對象轉換爲字符串的結果(通常是「[Object object]」)。 – Quentin

+0

OT:您應該考慮使用jQuery而不是原生XMLHttpRequest,它具有非常強大的AJAX功能,易於使用。 – th3falc0n

+0

你現在擁有的JavaScript將會工作得很好(除了我之前指出的問題,jQuery不會幫忙)。沒有必要爲您的頁面添加jQuery的重量。 – Quentin

回答

1

如果要使用原始post數據,以獲得JSON嘗試:

$json = json_decode(file_get_contents("php://input")); 

JS例如:

var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance 
xmlhttp.open("POST", "/json-handler"); 
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 
xmlhttp.send(JSON.stringify({key:"value", key:"value"})); 
+0

如果發送的內容是JSON,那就行了。 – Quentin

3

在客戶端將您的JSON字符串化。

window.onload = function() { 
    var json = { 
     hello : 'howareyou', 
     good : 'yes i am good', 
     toast : 'i love toast' 
    } 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
     if(xhr.readyState == 4 && xhr.status == 200) { 
      alert(xhr.responseText); 
     } else { 
      alert("no"); 
     } 
    } 
    xhr.open('POST', 'json.php', true); 
    xhr.send(JSON.stringify(json)); 
} 

從原始請求主體解碼JSON。

$json = json_decode(file_get_contents("php://input")); 
+0

我可以使用$ _POST ['json']或其他東西將數據先存入變量,然後對其進行解碼。 – user3105607

+0

僅當您將JSON嵌入到某些表單URL編碼數據中時纔有效。這是毫無意義的。 – Quentin

+0

合理全面的答案在這裏。儘管如此,您應該爲請求設置內容類型標題。 – Quentin