我无法从jQuery Ajax请求中获取PHP中的PUT数据



当我尝试访问表单数据时,我使用jQuery AJAX发送PUT请求,我得到这个响应:

阵列([------WebKitFormBoundary4TPPQZu7B7WFrUsv Content-Disposition:_form-data;_name] =>"id"7------WebKitFormBoundary4TPPQZu7B7WFrUsv Content-Disposition: form-data;name ="naam"Eiusmod alias test do------WebKitFormBoundary4TPPQZu7B7WFrUsv Content-Disposition: form-data;name ="email"zatapohopu@mailinator.com------WebKitFormBoundary4TPPQZu7B7WFrUsv Content-Disposition: form-data;name ="adres"Voluptates adipisici------WebKitFormBoundary4TPPQZu7B7WFrUsv Content-Disposition: form-data;name ="telefoonnummer"0612345678------WebKitFormBoundary4TPPQZu7B7WFrUsv Content-Disposition: form-data;name ="rol"4------WebKitFormBoundary4TPPQZu7B7WFrUsv——)
警告:未定义数组键"id"在C:xampphtdocsP08hoornhekapigebruiker.phpon line22

我也无法获得数组键。这是我的jQuery AJAX请求:

$('#bewerkGebruikerForm').on('submit', function(event) {
event.preventDefault();
const formData = new FormData(this);
// Opslaan gegevens gebruiker
$.ajax({
url: 'http://localhost/P08/hoornhek/api/gebruiker.php',
type: 'put',
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(response) {
if(response['success']) {
$('#bewerkGebruikerModal').hide();
window.location.reload();
} else {
showErrors(response.errors);
}
},
error: function(error) {
showErrors(error.errors);
}
});
});
这是我的PHP (API)代码:
$requestMethod = $_SERVER['REQUEST_METHOD'];
switch ($requestMethod) {
case "GET":
getGebruiker();
case "POST":
createGebruiker();
break;
case "PUT":
parse_str(file_get_contents("php://input"), $_PUT);
print_r($_PUT);
echo $_PUT['id'];
updateGebruiker();
break;
case "DELETE":
parse_str(file_get_contents("php://input"), $_DELETE);
deleteGebruiker();
break;
default:
exit();
}

对于我的GET, POST和DELETE请求,一切工作正常。我做错了什么?

不能通过$_REQUEST访问PUT请求中的数据。您需要这样的内容:

case "PUT":
parse_str(file_get_contents("php://input"), $sent_vars);
echo json_encode(['response'=>$sent_vars['id']]); // use an array and json_encode toavoid messy string concatenation
updateGebruiker();
break;

参见从PHP访问传入的PUT数据

最新更新