微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用xmlHttpRequest从php发送和接收数据

如何解决如何使用xmlHttpRequest从php发送和接收数据

我正在尝试将一些数据发送到 PHP 脚本,然后返回一些其他数据。我不知道如何访问我发送到 PHP 脚本的数据。 stackoverflow 上的这篇文章没有帮助:Reading JSON POST using PHP Is the sent data in $_POST?它是在 $data 还是 $params 中?我如何访问它并打印出来。

这是我所拥有的:

index.html:

    .custom-input-container {
        display: flex;
        flex-direction: column;
        min-width: 300px;
        background: orange;
    }
    .custom-input-container .input-group {
        display: flex;
        flex-direction: row;
    }
    .custom-input-container .input-group input {
        width: 50%;
        height: 56px;
    }
    .custom-input-container input {
        height: 56px;
    }

xhr.js

<!DOCTYPE html>
<html lang="en">
<head>
  <Meta charset="UTF-8">
  <Meta name="viewport" content="width=device-width,initial-scale=1.0">
  <Meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Http Requests & JavaScript</title>
  <link rel="stylesheet" href="app.css">
  <script src="xhr.js" defer></script>
</head>
<body>
  <section id="control-center">
    <button id="get-btn">GET Data</button>
    <button id="post-btn">POST Data</button>
  </section>
</body>
</html>

data.PHP

const getBtn = document.getElementById('get-btn');
const postBtn = document.getElementById('post-btn');




const sendHttpRequest = (method,url,data) => {
    const promise = new Promise((resolve,reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open(method,url);
        xhr.responseType = 'json';
        if (data){
            xhr.setRequestHeader('Content-Type','application/json');
        }

        xhr.onload = () => {
            resolve(xhr.response);
        }
        xhr.send(JSON.stringify(data));
    });
    console.log(promise);
    return promise;
};


const getData = () => {
    sendHttpRequest('GET','http://localhost/async/data.json').then(responseData => {
        console.log(response);

    });
};

const sendData = () => {
    sendHttpRequest('POST','http://localhost/async/data.PHP',{
        email: 'drcrocket@gmail.com',password: 'bowie'
    }).then(responseData => {
        console.log(responseData);
    });
};

getBtn.addEventListener('click',getData);
postBtn.addEventListener('click',sendData);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。