首页 > 解决方案 > 无法访问 php 中发布的数据

问题描述

我正在使用reactjsPHP尝试POST使用fetch API. 数据已成功发布,但服务器端的数据格式很奇怪,我无法使用它。

这是我的代码的一部分:

Javascript

var url = "http://cyg.com/router.php";

var data = {
  service: 'Grade',
  programme: this.state.programme,
  enrolment: this.state.enrolment
};

fetch(url, {
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json'
  }
})
.then(
  res => res.json()
)
.then(
  (result) => {
    console.log(result);
    //code to handle result here...
  },
  (error) => {
    console.log(error);
    //code to handle error here...
  }
);

PHP

<?php
  print_r($_POST); // here just to verify posted data. Remove later.
  $service = $_POST['service'];
  $programme = $_POST['programme'];
  $enrolment = $_POST['enrolment'];
  //some to code to process request....
?>

在发布数据时,它给出的错误是 undefined indexservice和.programmeenrolment

在检查浏览器XHR POST中的请求时console,我得到了请求的参数和响应。

参数 发布的数据格式

回复 返回数据的格式

您可以在Response (2nd Image) 中看到,值$_POST的格式为:

Array
(
    [{"service":"Grade","programme":"BCA","enrolment":"147996460"}] => 
)

我无法弄清楚问题的原因。但是,如果我按以下方式更改 Javascript,一切正常。

修改后的 JavaScript

var url = "http://cyg.com/router.php";

/*var data = {
  service: 'Grade',
  programme: this.state.programme,
  enrolment: this.state.enrolment
};*/

var data = "service=Grade&programme="+this.state.programme+"&enrolment="+this.state.enrolment;

fetch(url, {
  method: 'POST',
  body: data,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json'
  }
})
.then(
  res => res.json()
)
.then(
  (result) => {
    console.log(result);
    //code to handle result here...
  },
  (error) => {
    console.log(error);
    //code to handle error here...
  }
);

在更改 JavaScript 时,我观察到请求参数的格式也发生了变化,如下所示:- 发布的数据格式

谢谢你!!

标签: javascriptphpfetch

解决方案


推荐阅读