【问题标题】:PHP file does not receive variable from axios postPHP文件没有从axios post接收变量
【发布时间】:2021-11-03 00:56:02
【问题描述】:

我是 Vue 的新手,对于这个项目,我试图将可变的客户名称值传递给 PHP 文件,它将在其中搜索客户名称。我可以在 stackoverflow link 之后从 axios.post 传递值,但我的 PHP 文件仍然没有接收或打印出该值。

有没有办法从 axios.post 传递值并在 PHP 文件中接收/打印出来?

查看

<div id="app">
  <input type="text" v-model="customerName" placeholder="Enter customer first name">
  <button type="button" @click="buttonClicked()">
    Click
  </button>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

方法

new Vue({
  el: "#app",
  data: {
    customrName : '',
  },
  methods: {
    buttonClicked(){
      
      var form = new FormData();
      form.append('customerName', this.customerName);

      axios.post(url,{
        form
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    }
  }
})

PHP 文件

header("Content-type: application/json";
$data = json_decode(file_get_contents("php://input"), TRUE);
$CustomerName = $data['customer_name'];
echo $CustomerName;  /** does not print out the customer name typed from VIEW input field **/

【问题讨论】:

  • 您在 JS 中的 FormData 对象中将数据添加为 customerName,但在 PHP 中尝试将其检索为 customer_name。这是两个完全不同的名称/键。
  • 您的 Vue 组件中也有错字。您的数据对象包含 customrName 属性而不是 customerName

标签: javascript php vue.js axios


【解决方案1】:

你有四个问题。

您发送的数据格式

您正在发布一个FormData 对象。这将生成一个多部分请求,而不是 JSON 请求。

$_POST 读取数据。远离php://input

您的字段名称

您发送customerName 并尝试阅读customer_name。选择一个并坚持下去。

您响应的内容类型

您说header("Content-type: application/json";,但您正在输出用户输入的原始内容。这是text/plain 而不是application/json

要么使用正确的内容类型,要么将输出编码为 JSON。

你也打错了。

header 的调用中缺少)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2019-12-30
    相关资源
    最近更新 更多