【发布时间】:2019-02-23 23:59:43
【问题描述】:
我正在尝试发送POST request via PHP from AJAX。我用Postman 检查了API。它工作正常。但它没有在 PHP 中执行。它也没有显示在网络选项卡中。
我在 Stack Overflow 中看到了很多用于发出 POST 请求的示例并进行了尝试。但是我不知道我哪里出错了?
我在这里附上了 JS 代码和 PHP 代码
JavaScript 代码
function editUser(toid, name, mobile, mail, pin, addr, state, dis, subdis, role, user) {
$.ajax({
type: "POST",
url: "edituser.php",
dataType: 'html',
data: {
id: toid,
fullname: name,
phone: mobile,
email: mail,
address1: addr,
state: state,
district: dis,
subdistrict: subdis,
pincode: pin,
usertype: user,
role: role,
token: apptoken,
},
success: function (response) {
visibility(false);
console.log("Response > > " + response);
if (response.status == "SUCCESS") {
swal("Updated User", " Information Updated Successfully!", "success");
}
loadData();
}
});
}
PHP 代码
<?php
// where are we posting to?
$url = 'http://api.tech.com/api/UpdateUser';
// what post fields?
$fields = array(
'id' => $_POST['id'],
'fullname' => $_POST['fullname'],
'phone' => $_POST['phone'],
'email' => $_POST['email'],
'address1' => $_POST['address1'],
'state' => $_POST['state'],
'district' => $_POST['district'],
'subdistrict' => $_POST['subdistrict'],
'pincode' => $_POST['pincode'],
'usertype' => $_POST['usertype'],
'role' => $_POST['role'],
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
$token = $_POST['token'];
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("AppToken: $token",
"Content-Type: application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// execute post
$result = curl_exec($ch);
echo $result;
// close connection
curl_close($ch);
?>
更新:
发送到 API ($url) 的请求未显示在“网络”选项卡中。但是显示了对 edituser.php 的请求。
【问题讨论】:
-
你不能回显数组 echo json_decode($result);,你的意思是 json_encode 吗?
-
网络选项卡根本不显示发出的请求?控制台有错误吗?
-
您是否尝试使用 PHP 接收数据?您的 PHP 代码并不表明您是。请澄清
-
PHP 代码实际上表明...
$_POST是一个全局变量,在收到帖子时填充。 -
"它没有出现在网络选项卡中" 那么你的
editUser()函数可能没有被调用。
标签: php ajax curl post php-curl