[英]PHP $_SERVER['REQUEST_METHOD'] always returning GET with AJAX post
I am trying to set up an api for my website.我正在尝试为我的网站设置 api。 I would like to have a single page that does a different action depending on the request method.
我想要一个页面,根据请求方法执行不同的操作。 ie.
IE。 GET to get a resource, POST to create a new one, PUT to update and DELETE to delete.
GET 获取资源,POST 创建新资源,PUT 更新,DELETE 删除。 I am testing the
$_SERVER['REQUEST_METHOD']
variable to see which function I should run but for some reason it is always showing as get regardless of my ajax request.我正在测试
$_SERVER['REQUEST_METHOD']
变量以查看我应该运行哪个函数,但由于某种原因,无论我的 ajax 请求如何,它总是显示为 get。
Page 1第 1 页
var data = {
store_id: id,
reward: reward,
disclaimer: disclaimer,
period: period,
active: active
}
//make request to save item
$.ajax({
type: "POST",
url: 'http://' + '<?php echo $base_url; ?>' + 'api/birthday',
data: data,
dataType: 'json',
//headers: {"X-HTTP-Method-Override": "POST"},
success: function(obj){
console.log(obj);
$('#save-modal').dialog('open');
},
error: function(xhr, textStatus, errorThrown){
console.log(arguments);
console.log(xhr + '' + textStatus + ' ' + errorThrown);
}
});
Page 2第2页
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if( isset($_REQUEST['store_id']) &&
isset($_REQUEST['reward']) &&
isset($_REQUEST['disclaimer']) &&
isset($_REQUEST['period']) &&
isset($_REQUEST['active']) &&
is_numeric($_REQUEST['active'])){
exit(json_encode(update_birthday_reward(filter_var($_REQUEST['store_id'], FILTER_SANITIZE_NUMBER_INT), filter_var($_REQUEST['reward'], FILTER_SANITIZE_STRING), filter_var($_REQUEST['disclaimer'], FILTER_SANITIZE_STRING), filter_var($_REQUEST['period'], FILTER_SANITIZE_STRING), filter_var($_REQUEST['active'], FILTER_SANITIZE_NUMBER_INT))));
}else{
exit(json_encode($_SERVER['REQUEST_METHOD']));
}
}else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_REQUEST['store_id'])){
exit(json_encode(get_birthday_reward($_REQUEST['store_id'])));
}else{
exit(json_encode($_SERVER['REQUEST_METHOD']));
}
}
Looks like your request is being redirected to an actual PHP file, that's why you get POST first, which immediately translates to a GET request.看起来您的请求正在被重定向到一个实际的 PHP 文件,这就是您首先获得 POST 的原因,它立即转换为 GET 请求。
Try adding actual PHP file, like .../birthday/index.php
, instead of .../birthday/
.尝试添加实际的 PHP 文件,例如
.../birthday/index.php
,而不是.../birthday/
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.