首页 > 解决方案 > 如何在 PHP 中检索使用 fetch() 从 React js 发送的数据?

问题描述

我想将我的表单数据从react js应用程序发送到我的后端PHP程序。为了发送数据,我使用了fetch()in react js。以下是我的反应 js 代码:

import React, { Component } from 'react';

class Form extends Component{
    constructor(props){
        super(props);
        this.state = {
            username:''
        }
    }

    submitHandler = async (event) => {
        event.preventDefault();
        console.log(this.state.username);
        const data = this.state.username;
        await fetch("http://localhost:9090/assign/getApi.php",{
            method:'POST',
            headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({data})
        }).then((res)=>console.log(res));

    }

    render(){
        return(
            <div className="form">
                <form method="POST" onSubmit={this.submitHandler}>
                    <input type="text" placeholder="name" onChange={(event)=>{
                        this.setState({
                            username:event.target.value
                        });
                    }} value={this.state.username} />
                    <input type="submit" value="click" name="submit" />
                </form>
            </div>
        );
    }

}

export default Form;

如何在我的 PHP 代码中检索这些数据?目前,我只是这样做,但输出是空的Array()

<?php
print_r($_POST);
?>

标签: javascriptphpreactjs

解决方案


您应该在输入前添加一个名称。name="name"

<input type="text" name="name" placeholder="name" onChange={(event)=>{
                        this.setState({
                            username:event.target.value
                        });
                    }} value={this.state.username} />

如果你将使用 fetch 那么你应该路径参数:

await fetch("http://localhost:9090/assign/getApi.php",{
      method: 'POST',
      headers: new Headers({
                 'Content-Type': 'application/x-www-form-urlencoded',
        }),
      body: "name= " + data

在 php 中:

<?php

$name = $_POST['name'];
echo $name;

推荐阅读