简体   繁体   English

使用 vanilla javascript 将数据发布到 php 并将其取回

[英]POST data to php using vanilla javascript and get it back

I am trying to send variable to php using javascript and trying to receive back and alert that variable.我正在尝试使用 javascript 将变量发送到 php 并尝试接收并提醒该变量。 But $_POST['data'] doesn't get a data that I pass and $obj is always null.但是$_POST['data']没有得到我传递的数据并且$obj始终为空。

If I just echo "some text";如果我只是echo "some text"; it alerts that.它警告说。

Here is my javascript code:这是我的 javascript 代码:

getMessageType('some data'); //function call

function getMessageType(str)
{
    data = {'key': str};
    var xhr = new XMLHttpRequest();
    var url = "test.php";
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    console.log(data); //Object {key: "some data"}
    xhr.send(data);

    xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
          console.log(xhr.responseText);
        }
    };
}

Here is my PHP code:这是我的PHP代码:

<?php       
$obj = $_POST['key'];
echo $obj;

What I am doing wrong ?我做错了什么?

Any help is appreciated.任何帮助表示赞赏。 Thanks谢谢

You are posting the data with the content-type application/x-www-form-urlencoded .您正在使用内容类型application/x-www-form-urlencoded发布数据。

Therefore your data must be form encoded :因此,您的数据必须进行形式编码

data = "key="+str;

You can check this in your browser if the POST info has any "form data"如果 POST 信息有任何“表单数据”,您可以在浏览器中进行检查

If you need to pass JSON data (object) having content-type application/x-www-form-urlencoded you need to convert it in text format:如果您需要传递具有内容类型application/x-www-form-urlencoded 的JSON 数据(对象),则需要将其转换为文本格式:

  var params = "";
    for (key in data) {
        params += encodeURIComponent(key)+"="+encodeURIComponent(data[key])+"&";
    }

and then send it然后发送

xhr.send(params);

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

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