简体   繁体   中英

Get JSON data from AJAX POST send

I need to get some JSON data from and AJAX function in PHP This is what i've written so far but not sure exactly what to do on the PHP side. 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>

Stringify your JSON on the client side.

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));
}

Decode the JSON from the raw request body.

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

If you want to use raw post data, to get JSON try:

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

JS example:

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"}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM