我问了另一个与RESTful服务相关的问题here,还有另一个涉及DELETE(PUT)的问题:
我希望使用我的PUT发送用户凭据(用户名/密码)的情况。到目前为止,这是我的DELETE服务:
$http_req = $_SERVER["REQUEST_METHOD"];
switch ($http_req) {
case DELETE:
$user = $acct->read($_REQUEST["usernameDel"], $_REQUEST["passwordDel"]); // this method used to read db table with 1 record
if (!empty($_REQUEST["delTaskId"]) && isset($_REQUEST["usernameDel"]) && isset($_REQUEST["passwordDel"])) {
if ($user == true) {
$delete = fopen("php://input", "r");
$data = stream_get_contents($deleted);
$params;
parse_str($data, $params);
$dropped = $mgr->delete($params["id"]) // calls the method that deletes a particular row based on its id
echo $dropped;
}
}
}
这是我正在使用的html页面。我将其更新为:
<form action="TaskService.php" method="POST">
<label for="usernameDel">Username</label>
<input type="text" name="usernameDel" id="usernameDel" required/><br />
<label for="passwordDel">Password</label>
<input type="password" name="passwordDel" id="passwordDel" required/><br />
<label for="delTaskId">Task ID</label>
<input type="text" name="delTaskId" id="delTaskId" required/><br /><br />
<button type="button" id="btnDelete">Delete Task</button><br /><br />
</form>
这是我的ajax代码(编辑 - 现在使用@Devs修改):
$("#btnDelete").click(function() {
$.ajax({
method: "DELETE",
url: "TaskService.php",
data: { 'username':$("#usernameDel").val(), 'password': $("#passwordDel").val(), 'id': $("#delTaskId").val()},
success: function(theResponse) {
alert(theResponse);
}
});
});
目前它返回200响应,但是给了我为我的帐户课程输入的错误消息(返回&#34;找不到帐户&#34;。
我的直觉告诉我它与我的$_REQUEST[]
超级全球有关,因为它没有对表格动作做任何事情,但我不太熟悉通过ajax传递信息
想法?
答案 0 :(得分:0)
刚安排了ajax格式,php代码中也有一些语法错误。
注意:从未测试过
<强>的Ajax 强>
$(document).ready(function(){
$("#btnDelete").click(function() {
$.ajax({
method: "DELETE",
url: "TaskService.php",
data: { 'username':$("#usernameDel").val(), 'password': $("#passwordDel").val(), 'id': $("#delTaskId").val()},
success: function(theResponse) {
// Output
alert(theResponse); // comment this
}
});
});
});
<强> TaskService.php 强>
<?php
$http_req = $_SERVER["REQUEST_METHOD"];
switch ($http_req) {
case DELETE:
$user = $acct->read($_REQUEST["username"], $_REQUEST["password"]); // this method used to read db table with 1 record
if ($user == true) {
$delete = fopen("php://input", "r");
$data = stream_get_contents($deleted);
$params;
parse_str($data, $params);
$dropped = $mgr->delete($params["id"]); // calls the method that deletes a particular row based on its id
echo $dropped;
}
break;
}
?>
答案 1 :(得分:0)
找出为什么我的验证不起作用!我觉得很失明!
我忽略了删除操作将用户名,密码和id作为参数的事实....因此,验证不起作用,因为&#34; php://输入&#34;文件尚未打开,无法通过所有3个参数进行解析。
这是我更新的PHP:
// I needed to access the file FIRST before doing anything with the parameters passed from AJAX
$deleted = fopen("php://input", "r");
$data = stream_get_contents($deleted);
$params;
parse_str($data, $params);
$user_auth = $acctMgr->readAcct($params["username"], $params["password"]);
if ($user_auth == true) {
$rows = $mgr->delete($params["id"]);
echo $rows;
} else {
echo "User not authenticated";
}