简体   繁体   English

从AJAX POST发送获取JSON数据

[英]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. 我需要从PHP中获取一些JSON数据,并在PHP中获得AJAX函数。这是我到目前为止编写的内容,但不确定在PHP方面要做什么。 JS: 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:

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

HTML: 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. 在客户端字符串化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));
}

Decode the JSON from the raw request body. 从原始请求主体解码JSON。

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

If you want to use raw post data, to get JSON try: 如果要使用原始发布数据,请尝试获取JSON:

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

JS example: 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.

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