简体   繁体   English

原版 Javascript 和 Ajax - $_POST 为空

[英]Vanilla Javascript and Ajax - $_POST is empty

I send data with ajax using the POST method.我使用 POST 方法通过 ajax 发送数据。

Once the data are sent $_POST['my_value'] remains empty.发送数据后,$_POST['my_value'] 保持为空。

However the expected value is in $_GET['my_value'].但是,预期值在 $_GET['my_value'] 中。

Here is my ajax call:这是我的 ajax 电话:

loadAjaxDoc( 'https://www.mypage.com/?my_value=test', 1000, initGame );

function loadAjaxDoc( url, timeout, cFunction ) {

    var xhr;

    setTimeout(function() {

        xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function() {

            elements.interludeCountdownDiv.innerHTML = '[[%doodles.game_loaded]]';

            if ( this.readyState == 4 ) { 

                elements.interludeCountdownDiv.innerHTML = '[[%doodles.game_loading_state4]]';

                if ( this.status === 0 || ( this.status >= 200 && this.status < 400 ) ) {

                    if ( this.status == 200 ) {

                        cFunction( this );

                    }

                }

            }

        };

        xhr.open( 'POST', url, true );
        xhr.timeout = timeout;

        setTimeout( function() {

            xhr.send( null );

        }, 1000 );

    }, 1000 );

}

Am i doing something wrong?难道我做错了什么?

Can someone give a hand for this?有人可以帮忙吗? Any help appreciated:)任何帮助表示赞赏:)

The PHP superglobals $_POST and $_GET are not directly related to the HTTP request method. PHP 超全局变量$_POST$_GET与 HTTP 请求方法没有直接关系。

$_GET is populated with data from the URL's query string. $_GET填充了来自 URL 查询字符串的数据。

$_POST is populated with data from the request body (if it uses a supported encoding like application/www-url-encoded ). $_POST填充来自请求正文的数据(如果它使用支持的编码,如application/www-url-encoded )。

We can't see what URL you are passing, but since you say the data is showing up in $_GET you must have put the data there.我们看不到您传递的 URL 是什么,但既然您说数据显示在$_GET中,您肯定已经将数据放在那里。

We can see what you put in the request body — null — so the body will be empty.我们可以看到您在请求正文中放入的内容 — null — 所以正文将为空。


If you want to populate the body you could do something like:如果要填充主体,可以执行以下操作:

const body = new FormData();
body.append('my_value', "some value");
xhr.send(body);

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

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