我正在尝试为我的网站设置api。我希望有一个页面根据请求方法执行不同的操作。即。 GET获取资源,POST创建新资源,PUT更新和DELETE删除。我正在测试$_SERVER['REQUEST_METHOD']
变量以查看我应该运行哪个函数但由于某种原因它始终显示为get而不管我的ajax请求。
Page 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);
}
});
第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']));
}
}
答案 0 :(得分:1)
看起来您的请求被重定向到实际的PHP文件,这就是您首先获得POST的原因,这会立即转换为GET请求。
尝试添加实际的PHP文件,例如.../birthday/index.php
,而不是.../birthday/
。