javascript - 无法访问 php 中发布的数据
问题描述
我正在使用reactjs
并PHP
尝试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
和.programme
enrolment
在检查浏览器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 时,我观察到请求参数的格式也发生了变化,如下所示:-
谢谢你!!
解决方案
推荐阅读
- kotlin - 为什么在 catch 块中更改调度程序会抛出 VerifyError
- flutter - 如何检测颤动中的键盘点击?
- swift - 在范围 swift 5 中找不到“视图”
- javascript - jquery全选复选框不会在单个复选框上触发更改事件
- rest - Shopee OpenAPI 1.0 Authorization and Authentication 总是返回“No partner_id”
- geopandas - 如何使用 geopandas 计算距离
- python-3.x - 使用 OpenCV 比较列表并显示结果
- python - 如何处理python包?
- node.js - 计算没有重复字段mongodb的文档
- javascript - 无法使用 node.js 解决 mysql 中的错误 1251