简体   繁体   English

AJAX JSON发布到PHP

[英]AJAX JSON Post to PHP

I'm trying to post JSON String via AJAX to PHP, but all examples not work. 我正在尝试通过AJAX将JSON字符串发布到PHP,但是所有示例均不起作用。
First of all I learn https://www.w3schools.com/js/js_json_php.asp 首先,我学习https://www.w3schools.com/js/js_json_php.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_db_post https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_db_post
Then i write own code. 然后,我编写自己的代码。 But no one of my example code below not working. 但是我下面的示例代码中没有一个不起作用。 And return one result: 并返回一个结果:

index.php:6:string '[object Object]' (length=15)
index.php:7:null
index.php:8:null

First variant: 第一个变体:

<?php

    $JsonPost   = file_get_contents('php://input');
    if ($JsonPost != null) {
        var_dump($JsonPost);
        var_dump(json_decode($JsonPost, true));
        var_dump(json_decode($JsonPost));
    } else {
    ?>
    <html> 
        <script type="text/javascript">
            var RequestObject = new XMLHttpRequest();
            RequestObject.open("POST", window.location.href, true)
            RequestObject.setRequestHeader('Content-type', 'application/json');

            var SomeObject      = {};
            SomeObject.Field1   = 'lalala';
            SomeObject.Array1   = [
                'lala1', 'lala2'
            ];

            RequestObject.onreadystatechange = function() {
                if (RequestObject.readyState == 4 && RequestObject.status == 200) {
                    document.getElementById("body").innerHTML = RequestObject.responseText;
                }
            };

            var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
            RequestObject.send(JsonStr);
        </script>
    <body id="body"></body> 
    </html>
    <?php 
    }
    ?>

Second variant: 第二个变体:

<?php

if (isset($_POST['JsonPost'])) {
    var_dump($_POST['JsonPost']);
    var_dump(json_decode($_POST['JsonPost'], true));
    var_dump(json_decode($_POST['JsonPost']));
} else {
?>
<html> 
    <script type="text/javascript">
        var RequestObject = new XMLHttpRequest();
        RequestObject.open("POST", window.location.href, true)
        RequestObject.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');

        var SomeObject      = {};
        SomeObject.Field1   = 'lalala';
        SomeObject.Array1   = [
            'lala1', 'lala2'
        ];

        RequestObject.onreadystatechange = function() {
            if (RequestObject.readyState == 4 && RequestObject.status == 200) {
                document.getElementById("body").innerHTML = RequestObject.responseText;
            }
        };

        var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
        RequestObject.send("JsonPost=" + JsonStr);
    </script>
<body id="body"></body> 
</html>
<?php 
}

?>

Please help. 请帮忙。
PHP Version 5.6.28 PHP版本5.6.28
XAMPP v3.2.2 on Windows 10 (64-bit) Windows 10(64位)上的XAMPP v3.2.2
Browser Chrome 56.0.2924.87 (64-bit) 浏览器Chrome 56.0.2924.87(64位)

UPDATED 更新

Working Example. 工作示例。

<?php

$JsonPost   = file_get_contents('php://input');
if ($JsonPost != null) {
    var_dump($JsonPost);
    var_dump(json_decode($JsonPost, true));
    var_dump(json_decode($JsonPost));
} else {
    ?>
<html> 
    <script type="text/javascript">
        var RequestObject = new XMLHttpRequest();
        RequestObject.open("POST", window.location.href, true)
        RequestObject.setRequestHeader('Content-type', 'application/json');

        var SomeObject      = {};
        SomeObject.Field1   = 'lalala';
        SomeObject.Array1   = [
            'lala1', 'lala2'
        ];

        RequestObject.onreadystatechange = function() {
            if (RequestObject.readyState == 4 && RequestObject.status == 200) {
                document.getElementById("body").innerHTML = RequestObject.responseText;
            }
        };

        //var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
        var JsonStr = JSON.stringify(SomeObject);
        RequestObject.send(JsonStr);
    </script>
<body id="body"></body> 
</html>
<?php 
}
?>

Many thanks to all who answered. 非常感谢所有回答的人。

Change in you Second variant this: 在您的第二个变体中更改:

    var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
    RequestObject.send("JsonPost=" + JsonStr);

to

    RequestObject.send("JsonPost=" + JSON.stringify(SomeObject));

Why: 为什么:

  • var JsonStr = { creates an new real javascript object var JsonStr = {创建一个新的真实javascript对象
  • but this object can not used with + to concate it 但是该对象不能与+一起使用
 var JsonStr = {JsonPost: JSON.stringify(SomeObject)}; RequestObject.send(JsonStr); 

Here you are: 这个给你:

  1. Creating some JSON 创建一些JSON
  2. Setting the JSON as the value of an object property 将JSON设置为对象属性的值
  3. Implicitly converting the object to a string (which will be "[object Object]" ) 隐式地将对象转换为字符串(将为"[object Object]"
  4. Sending that string as the request body 发送该字符串作为请求正文

But since you are trying to post JSON you should skip steps 2 and 3 … just pass the JSON: 但是,由于您尝试发布JSON,因此应该跳过步骤2和3… 只需传递JSON:

RequestObject.send(JSON.stringify(SomeObject));

Your problem is this: 您的问题是这样的:

var JsonStr = {JsonPost: JSON.stringify(SomeObject)};

that is still a javasript object, you have to stringifly the whole thing 那仍然是一个javasript对象,您必须将整个事情严格化

so this should wok: 所以应该这样:

var JsonStr = JSON.stringify({JsonPost: SomeObject});
RequestObject.send(JsonStr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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