在 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'");
?>
I'm trying to run a quick php script when users leave my website, and also pass a variable from my javascript to php but i'm not quite sure how to include the php file and pass it a var. But it's not actually running the php script. any ideas?
(the javascript gets the username from an external activity function, and i know that works i tested the var on an alert and its there.)
My 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>
My RemoveUserOnDisconnect.php File:
<?php
mysql_connect("mysql.mysql.com", "username", "password");
mysql_select_db("my_db");
mysql_query("DELETE FROM my_table WHERE username = '$username'");
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试 ajax 请求。根据您的 php 脚本,您将需要
$.post
或$.get
jQuery:
编辑:
您的 php 脚本应该引用
$_POST
数组,如果你使用我上面的代码。Try an ajax request. Depending on your php script you will need
$.post
or$.get
jQuery:
EDIT:
Your php script should reference the
$_POST
array if you use my code above.对 script/RemoveUserOnDisconnect.php?username=username 进行 ajax 调用。你不能将 PHP 包含在 Javascript 中,Javascript 在浏览器上执行,PHP 在服务器上执行。
Make an ajax call to scripts/RemoveUserOnDisconnect.php?username=username. You cannot include PHP with Javascript, Javascript executes on the browser, PHP executes on the server..
您需要对 PHP 脚本进行 AJAX 调用。您的 JavaScript 代码只会向 php 脚本发出后台请求,该脚本将执行这些 MySQL 语句。谷歌搜索 AJAX。推荐:学习 jQuery 并使用
$.get()
或$.post()
使用 ajaxYou need to make an AJAX call to the PHP script. Your javascript code will just make a background request to the php script which will execute those MySQL statements. Google up AJAX. Recommended: Learn jQuery and use ajax using
$.get()
or$.post()