我正在制作一个带有可以拖动图像的网站。然后我有一个 Javascript 代码,它可以检测用户在页面上通过 x 和 y 坐标拖动它们的位置。为此,我有以下代码:(house_position.js)
var offset = 0;
var xPos = 0; var yPos = 0;
$(文档).ready(函数(){ $(".item").draggable({ 遏制:'#house_wall1',
drag: function(){
offset = $(this).offset();
xPos = offset.left;
yPos = offset.top;
$('#posX').text('x: ' + xPos);
$('#posY').text('y: ' + yPos);
},
// Find original position of dragged image.
start: function(event, ui) {
// Show start dragged position of image.
var Startpos = $(this).position();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
},
// Find position where image is dropped.
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
}
});
});
除此之外,我还有一个通过按按钮运行的 AJAX 脚本。 <button onclick="houseAjax()">Save positions</button>
该脚本如下所示:
function houseAjax(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
$.post("update_house.php",{newx: xPos, newy: yPos},function(result){
});
}
}
xmlhttp.open("POST","update_house.php", true);
xmlhttp.send();
} 最后,我有 update_house.php,它应该使用准备好的语句将 x 和 y 值发送到数据库中。
<?php
require_once('includes/db_connect.php');
$newX = $_POST['newx'];
$newY = $_POST['newy'];
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('UPDATE house_room1 SET x = ?, y = ? WHERE `user_id`=?')) {
/* Bind parametres */
$stmt->bind_param('iii', $newX, $newY, $id);
/* Insert the parameter values */
$id = 1;
/* Execute the query */
$stmt->execute();
/* Close statement */
$stmt->close();
} else {
/* Something went wrong */
echo 'Something went terrible wrong' . $mysqli->error;
}
?>
我的问题是 x 和 y 值无法以某种方式正确地从 JS 解析为 PHP。这些值不会进入数据库,并且当所有这些代码运行时,数据库中不会发生任何事情。我知道这个问题可能存在于上面代码的各个方面,我希望有人能够找到我没有正确理解的地方。提前致谢。
更新: 当按下按钮时,数据库现在可以将 0 插入数据库,现在的问题似乎是关于跟踪 x 和 y 位置的 javascript 变量,该变量未正确解析到数据库。谢谢
最佳答案
我会检查您的 PHP 代码,即定义变量和构建查询的方式:
$newX = $_POST['newx'];
$newY = $_POST['newy'];
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('UPDATE house_room1 SET x = ?, y = ? WHERE `user_id`=?')) {
/* Bind parametres */
$stmt->bind_param('ddi', $newX, $newY, $id);
...
关于javascript - PHP、JS、AJAX 无法向数据库发送值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21888437/