在JavaScript中执行PHP脚本?
作者:互联网
当用户离开我的网站时,我正在尝试运行一个快速的php脚本,并且还将我的JavaScript变量传递给php,但我不太确定如何包含php文件并将其传递给var.但是它实际上并没有运行php脚本.有任何想法吗?
(JavaScript从外部活动函数获取用户名,我知道该方法对警报及其下的var进行了测试.)
我的JavaScript:
<script language="javascript" type="text/javascript">
var username = null;
function GetUsername(usernameff)
{
username = usernameff;
}
window.onbeforeunload = function ()
{
if (username != null)
{
<?php include("scripts/RemoveUserOnDisconnect.php?username=username");?>
}
}
</script>
我的RemoveUserOnDisconnect.php文件:
<?php
mysql_connect("mysql.mysql.com", "username", "password");
mysql_select_db("my_db");
mysql_query("DELETE FROM my_table WHERE username = '$username'");
?>
解决方法:
尝试ajax请求.根据您的PHP脚本,您将需要$.post或$.get
jQuery的:
<script language="javascript" type="text/javascript">
var username = null;
function GetUsername(usernameff){
username = usernameff;
}
window.onbeforeunload = function(){
if (username != null){
$.post('scripts/RemoveUserOnDisconnect.php', {username: username}, function(){
//successful ajax request
}).error(function(){
alert('error... ohh no!');
});
}
}
</script>
编辑:
如果您使用上面的代码,则您的PHP脚本应引用$_POST数组.
<?php
$username = $_POST['username'];
mysql_connect("mysql.mysql.com", "username", "password");
mysql_select_db("my_db");
mysql_query("DELETE FROM my_table WHERE username = '$username'");
?>
标签:onbeforeunload,javascript,php,variables,mysql 来源: https://codeday.me/bug/20191010/1885661.html