我已按照本教程here构建了一个简单的API 当用户单击某个房间时,系统会提示他们是否需要打扫房间,如果用户单击“是”,则会对我的API的更新部分提出ajax请求。该请求返回成功,但是由于某种原因数据库未更新。我知道连接到数据库没有问题,因为我可以从数据库读取信息没有问题。 以下是拨打电话的前端的一小段代码。
//loop through room cells and add click listener
var roomCells = document.getElementsByClassName("zui-sticky-col");
for (i=0; i<roomCells.length; i++) {
$(roomCells[i]).attr('data-room', i);
$(roomCells[i]).on('click tap', function() {
cleanFlag(this);
});
}
//destroy modal
$("body").on('click tap', '#closeIt', function() {
destroyModal();
});
//destroy modal
$("body").on('click tap', '.no', function() {
destroyModal();
});
//add clean event
$("body").on('click tap', '.yes', function() {
addClean();
});
//remove clean event
$("body").on('click tap', '.yesClean', function() {
removeClean();
});
//function to schedule clean flag
function cleanFlag($this) {
var attribute = $this.getAttribute("data-room");
roomClean = attribute;
$("body").addClass("lock");
$(".zui-scroller").addClass("lock");
$("body").append("<div class='overlay'></div>");
$("body").append("<div class='modal'></div>");
$(".modal").append("<p class='close'><i id='closeIt' class='far fa-times-circle fa-2x'></i></p>");
if (! $('[data-room='+roomClean+']').find('.fa-exclamation-circle').length) {
$(".modal").append("<p class='modalTxt'>Does This Room Need to Be Cleaned?</p>");
$(".modal").append("<div class='responseWrap'></div>");
$(".responseWrap").append("<div class='no'>No</div>");
$(".responseWrap").append("<div class='yes'>Yes</div>");
}
else {
$(".modal").append("<p class='modalTxt'>Has This Room Been Cleaned?</p>");
$(".modal").append("<div class='responseWrap'></div>");
$(".responseWrap").append("<div class='no'>No</div>");
$(".responseWrap").append("<div class='yesClean'>Yes</div>");
}
}
// function to add clean flag
function addClean() {
var temp = roomClean +1;
$.ajax({
type: "POST", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/update.php",
dataType:'text',
data:JSON.stringify( {"room": temp, "dirty": "1"}),
success : function(data) {
$('[data-room='+roomClean+']').append('<br><i class="fas fa-exclamation-circle"></i>');
},
failure: function(jqXhr, textStatus, errorMessage) {
console.log(" Sorry I can't do that right now. Please try again. ", errorMessage );
}
});
destroyModal();
}
// function to remove clean flag
function removeClean() {
var temp = roomClean +1;
$.ajax({
type: "POST", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/update.php",
dataType:'text',
data:JSON.stringify( {"room": temp, "dirty": "0"}),
success : function(data) {
$('[data-room='+roomClean+'] i').remove('.fa-exclamation-circle');
$('[data-room='+roomClean+'] br').remove();
},
failure: function(jqXhr, textStatus, errorMessage) {
console.log(" Sorry I can't do that right now. Please try again. ", errorMessage );
}
});
destroyModal();
}
// destroy modal
function destroyModal() {
$(".modal").remove();
$(".overlay").remove();
$("body").removeClass("lock");
$(".zui-scroller").removeClass("lock");
}
//function to schedule clean flag
function cleanFlag($this) {
var attribute = $this.getAttribute("data-room");
roomClean = attribute;
$("body").addClass("lock");
$(".zui-scroller").addClass("lock");
$("body").append("<div class='overlay'></div>");
$("body").append("<div class='modal'></div>");
$(".modal").append("<p class='close'><i id='closeIt' class='far fa-times-circle fa-2x'></i></p>");
if (! $('[data-room='+roomClean+']').find('.fa-exclamation-circle').length) {
$(".modal").append("<p class='modalTxt'>Does This Room Need to Be Cleaned?</p>");
$(".modal").append("<div class='responseWrap'></div>");
$(".responseWrap").append("<div class='no'>No</div>");
$(".responseWrap").append("<div class='yes'>Yes</div>");
}
else {
$(".modal").append("<p class='modalTxt'>Has This Room Been Cleaned?</p>");
$(".modal").append("<div class='responseWrap'></div>");
$(".responseWrap").append("<div class='no'>No</div>");
$(".responseWrap").append("<div class='yesClean'>Yes</div>");
}
}
//add room flag
function addRoomFlag(data) {
for (i=0; i < data.room.length; i++) {
if(data.room[i].dirty == 1) {
$('[data-room='+i+']').append('<br><i class="fas fa-exclamation-circle"></i>');
}
}
}
// here are ajax calls *********
// make json call for room status
$.ajax({
type: "get", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/read.php",
processData: true,
data: {},
dataType: "json",
success: function (data) {
addRoomFlag(data);
}
});
// function to add clean flag
function addClean() {
var temp = roomClean +1;
$.ajax({
type: "POST", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/update.php",
dataType:'text',
data:JSON.stringify( {"room": temp, "dirty": "1"}),
success : function(data) {
$('[data-room='+roomClean+']').append('<br><i class="fas fa-exclamation-circle"></i>');
},
failure: function(jqXhr, textStatus, errorMessage) {
console.log(" Sorry I can't do that right now. Please try again. ", errorMessage );
}
});
destroyModal();
}
// function to remove clean flag
function removeClean() {
var temp = roomClean +1;
$.ajax({
type: "POST", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/update.php",
dataType:'text',
data:JSON.stringify( {"room": temp, "dirty": "0"}),
success : function(data) {
$('[data-room='+roomClean+'] i').remove('.fa-exclamation-circle');
$('[data-room='+roomClean+'] br').remove();
},
failure: function(jqXhr, textStatus, errorMessage) {
console.log(" Sorry I can't do that right now. Please try again. ", errorMessage );
}
});
destroyModal();
}
.zui-sticky-col {
border-bottom: 0px;
border-right: 0px;
z-index:3;
text-align: center;
height: 60px;
min-width:100%;
width: 100%;
border-bottom: 1px solid rgba(255,255,255,0.1);
}
.modal {
width:80%;
z-index: 10;
position: fixed;
top: 50%;
left:50%;
transform: translate(-50%, -50%);
background-color:white;
padding-left:.8em;padding-right:.8em;
padding-bottom: 10px;
}
.overlay {
width:100%;
height: 100%;
z-index: 9;
position: fixed;
top: 0;
left:0;
background-color: rgba(0,0,0,0.5);
}
.modal input {
-webkit-appearance: none;
border-radius:none;
display:block;
width: 95%;
margin: 0 auto;
background-color:#3d3d3d;
color: #e84118;
font-size: 18px;
font-weight: 600;
padding: 16px 0px;
border-radius: 0;
border: 0px;
text-align: center;
}
.modalTxt {
padding: 15px 0px;
margin: 0;
font-size: 18px;
color: #3d3d3d;
font-weight: 600;
text-align: center;
}
.close {
padding: 10px 10px 0px 0px;
margin: 0;
color: #e84118;
font-weight: 600;
text-align: right;
}
#closeIt {
cursor: pointer;
}
.fa-times-circle {
color:inherit;
}
.lock {
overflow: hidden;
width: 100vw;
height: calc(100vh - 61px);
}
.responseWrap {
margin-top: 10px;
display: flex;
justify-content: space-around;
}
.no, .yes, .yesClean {
padding: .8em 1em;
border-radius: 5px;
cursor: pointer;
}
.no {
background-color: red;
color:white;
}
.yes, .yesClean {
background-color: green;
color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" rel="stylesheet"/>
<div class="zui-sticky-col">Room 1</div>
<div class="zui-sticky-col">Room 2</div>
<div class="zui-sticky-col">Room 3</div>
<div class="zui-sticky-col">Room 4</div>
<div class="zui-sticky-col">Room 5</div>
<div class="zui-sticky-col">Room 6</div>
<div class="zui-sticky-col">Room 7</div>
<div class="zui-sticky-col">Room 8</div>
<div class="zui-sticky-col">Room 9</div>
<div class="zui-sticky-col">Room 10</div>
<div class="zui-sticky-col">Room 11</div>
<div class="zui-sticky-col">Room 12</div>
以下是与该问题有关的我的API的一部分
// Rooms class (rooms.php)
<?php
class Rooms{
// database connection and table name
private $conn;
private $table_name = "********";
// object properties
public $room;
public $dirty;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// read rooms
function read(){
// select all query
$query = "SELECT
p.room, p.dirty
FROM
" . $this->table_name . " p
ORDER BY
p.room";
// prepare query statement
$stmt = $this->conn->prepare($query);
// execute query
$stmt->execute();
return $stmt;
}
// update the room
function update(){
// update query
$query = "UPDATE
" . $this->table_name . "
SET
dirty =:dirty
WHERE
room =:room";
// prepare query statement
$stmt = $this->conn->prepare($query);
// sanitize
$this->dirty=htmlspecialchars(strip_tags($this->dirty));
$this->room=htmlspecialchars(strip_tags($this->room));
// bind new values
$stmt->bindParam(':dirty', $this->dirty);
$stmt->bindParam(':room', $this->room);
// execute the query
if($stmt->execute()){
return true;
}
return false;
}
} ?>
// update (update.php) this is the main driver
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// include database and object files
include_once '../config/database.php';
include_once '../objects/rooms.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare product object
$rooms = new Rooms($db);
// get id of room to be edited
$data = json_decode(file_get_contents("php://input"));
// set ID property of product to be edited
$rooms->room = $data->room;
// set product property values
$rooms->dirty = $data->dirty;
// update the product
if($rooms->update()){
// set response code - 200 ok
http_response_code(200);
}
// if unable to update the room, tell the user
else{
// set response code - 503 service unavailable
http_response_code(503);
}
?>
我有一个感觉,这个问题与我用ajax发出的推送房间状态的呼叫有什么联系,但我不确定。我知道这是一堵代码墙,几乎没什么可做的,但是对您的帮助非常感谢。
答案 0 :(得分:1)
如上面的评论所述,问题出在代码上
var attribute = $this.getAttribute("data-room");
roomClean = attribute;
和
var temp = roomClean +1;
因为“ $ this.getAttribute(” data-room“);”返回一个字符串,您需要在添加之前先对其进行解析。
因此代码变为:
var temp = parseInt(roomClean)+1;
为进一步说明,我将更改功能:
addClean() | removeClean()
仅带有另一个参数化函数(您希望使用布尔值或数字1/0)
function cleanFunction(clean) {
var temp = roomClean +1;
$.ajax({
type: "POST", //rest Type
url: "https://alteredego.org/markiii/inn_api/rooms/update.php",
dataType:'text',
data:JSON.stringify( {"room": temp, "dirty": clean}),
success : function(data) {
$('[data-room='+roomClean+']').append('<br><i class="fas fa-exclamation-circle"></i>');
},
failure: function(jqXhr, textStatus, errorMessage) {
console.log(" Sorry I can't do that right now. Please try again. ", errorMessage );
}
});
destroyModal();
}