[英]Get JSON data from AJAX POST send
我需要從PHP中獲取一些JSON數據,並在PHP中獲得AJAX函數。這是我到目前為止編寫的內容,但不確定在PHP方面要做什么。 JS:
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>
在客戶端字符串化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"));
如果要使用原始發布數據,請嘗試獲取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"}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.