【问题标题】:How to simultaneously send and get data in React using axios?如何使用 axios 在 React 中同时发送和获取数据?
【发布时间】:2020-06-06 19:51:48
【问题描述】:

所以我在 React 中有这个 onClick 函数,其中一个 div 中的内容将根据另一个 div 中的选定项目而改变。该函数看起来像这样,它将发出一个 post 请求来发送要接收的数据,并发出一个 get 请求来获取实际数据。

handleClick(event) {
this.setState({
  selected: event.target.innerText
});

axios.post("/e-commerce_with_purephp/acom_cms_admin/database/serveData.php", {category: this.state.selected})
.then(res => console.log("Response: " + res.parse))
.catch(error => console.log("Error: " + error))

axios
.get("/e-commerce_with_purephp/acom_cms_admin/database/serveData.php")
.then(response => response.data)
.then(data => {
  this.setState({
    ItemData: data
  })
})
}

而我的serveData.php 看起来像这样

<?php
include("connection.php");

if ($_SERVER['REQUEST_METHOD'] == "POST") {
$category = $_POST['category'];
}

if ($_SERVER['REQUEST_METHOD'] == "GET") {
    $sql = "SELECT * FROM `$category`";
    $result = mysqli_query($connection, $sql);
    echo "[";
for ($i = 0; $i < mysqli_num_rows($result); $i++) {
    echo ($i > 0 ? ',' : '') . json_encode(mysqli_fetch_object($result));
}
echo "]";
  } 

?>

除非我定义了类别,否则这不能正常工作。但在这种情况下,它只能处理一个数据并且是硬编码的。我不想一键从数据库中提取所有数据,因为在现实世界中获取所有数据需要更长的时间。我是 Axios 的新手,我参考了网络上的某些文章。

【问题讨论】:

    标签: javascript php reactjs axios


    【解决方案1】:

    我认为这与数据类型有关。我已将其声明为 FormData 并添加了标头作为配置,现在一切正常

    let cat = new FormData()
    cat.append('category', event.target.innerText)
    
    axios({
      method: 'post',
      url: '/e-commerce_with_purephp/acom_cms_admin/database/serveData.php',
      data: cat,
      config: { headers: {'Content-Type': 'multipart/form-data' }}})
      .then(response => response.data)
      .then(data => {
        this.setState({
          ItemData: data
        })
      })
    

    【讨论】:

      【解决方案2】:
      1. [client JS] 你想一键搞定
      2. [后端 PHP] 不要在 PHP 中拆分这两个操作。不要在 POST 中设置类别,然后尝试在 GET 调用中使用它。这是两个不同的调用,PHP 不会在调用之间保留 $category 变量
      axios.post("/e-commerce_with_purephp/acom_cms_admin/database/serveData.php", {category: this.state.selected})
      .then(response => response.data)
      .then(data => {
        this.setState({
          ItemData: data
        })
      });
      })
      .catch(error => console.log("Error: " + error))
      

      【讨论】:

      • 我也认为你的应该可以。但我认为“serveData.php”没有正确接收 {category} 因为我的控制台一直说我来自 php 的 $category 未定义
      猜你喜欢
      • 2020-11-21
      • 2019-12-21
      • 2022-01-04
      • 2018-01-31
      • 2020-07-20
      • 2022-01-25
      • 2023-02-04
      • 2020-08-21
      • 2020-09-10
      相关资源
      最近更新 更多