是否有可能在JS代碼塊中有PHP命令?在JavaScript代碼中有一個PHP代碼塊
首先,我做一個表單和保存的東西:
<form id = "myForm" action = "myPage.php" method = "post">
<input type ="hidden" name = "action" value = "submit" ></input>
Name: <input type = "text" name = "name">
<button id = "sub"> Submit my name </button>
</form>
<?php
if(isset($_POST[ "action" ]) && $_POST[ "action" ] == "submit")
{
include_once('db.php');
$name = $_POST[ "name" ];
}
?>
在我的db.php
很簡單:
<?php
$conn = mysql_connect("localhost", "root", "");
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("myDatabase");
?>
我也有一個顯示用戶的鼠標點擊的座標的JS代碼:
script>
$(document).ready(function(e)
{
$('#ClickBox').click(function(e)
{
var coordX = (e.pageX - $(this).offset().left - ($(this).width() * 0.5));
var coordY = -(e.pageY - $(this).offset().top - ($(this).height() * 0.5));
alert(coordX + ' , ' + coordY);
});
});
</script>
所以,現在,我想保存X
和Y
座標在同一個數據庫中,也許在不同的表中。這是我試過的:
script>
$(document).ready(function(e)
{
$('#ClickBox').click(function(e)
{
var coordX = (e.pageX - $(this).offset().left - ($(this).width() * 0.5));
var coordY = -(e.pageY - $(this).offset().top - ($(this).height() * 0.5));
alert(coordX + ' , ' + coordY);
$coordX = $_POST[ "x" ];
$coordY = $_POST[ "y" ];
});
});
</script>
這是錯的,是不是?我該怎麼做呢?
在此先感謝,
。
。
。
。
。
。
編輯:
這是我如何解決它:
<script>
$(document).ready(function(e)
{
$('#ClickBox').click(function(e)
{
var coordX = (e.pageX - $(this).offset().left - ($(this).width() * 0.5));
var coordY = -(e.pageY - $(this).offset().top - ($(this).height() * 0.5));
alert(coordX.toFixed(1) + ' , ' + coordY.toFixed(1));
$.post("myMainPage.php", { action: "submitXY", vx: coordX.toFixed(1), vy: coordY.toFixed(1) }, function(data) { alert("DONE ... this alert can be removed"); }, "json");
});
});
</script>
<?php
if(isset($_POST[ "action" ]) && $_POST[ "action" ] == "submitXY")
{
include_once('db.php');
$myClickX = $_POST[ "vx" ];
$myClickY = $_POST[ "vy" ];
if(mysql_query("INSERT INTO click VALUES('$myClickX', '$myClickY')"))
echo "Successfully Inserted mouse click coordinates!";
else
echo "Insertion failed . .";
}
?>
我db.php
是一個單獨的文件,它到底是如何在原來的問題。 感謝所有幫助, ^ h
您可以使用Javascript嵌入PHP。 –