最好的方法是进行异步 JavaScript 和 XML调用 (AJAX)。PHP是一种服务器端语言,它在构建 HTML(因此,在 Javascript 之前)并显示给浏览器之前执行。
因此, Javascript与 PHP 交换变量和数据的唯一方法是进行 AJAX 调用(您总是可以使用表单提交或会话变量和cookie重新加载页面,但这不是最好的方式去如果行动重复太频繁。
在 AJAX 中,您可以创建另一个 PHP 页面来检查这两个值并返回您想要的任何内容。响应可以存储在 Javascript 变量中,甚至可以存储在JSON中。
我建议您阅读有关 AJAX 的更多信息,并了解PHP 如何使用它。
编辑:阅读您的评论后,我决定在这里放一个简单的例子。
Javascript(在您的 HTML 页面中)
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)
{
/*Here you should do what you want.
xmlhttp.responseText is the content of your PHP answer! */
var result = xmlhttp.responseText;
//I am parsing a JSON response, which is a specific, universal language
//To exchange data without losing formatting or anything else.
result = JSON.parse(result);
/* The we use the name of our PHP array key as a property
Here it is "response" (see PHP json_encode line) */
alert(result.response);
}
}
/* Change this URL for the PHP filename. we use the GET method to send data. */
/* You should always use the POST method when sending sensitive data */
xmlhttp.open("GET","getUserClicks.php?clicks="+count+"&username="+username,true);
xmlhttp.send();
PHP(这里是名为 getUserClicks.php 的文件)
<?php
if(!isset($_GET['username']) || !isset($_GET['clicks']))
die("Error");
$username = $_GET['username'];
$jsClicks = $_GET['clicks'];
$phpClicks = null;
#I am using the mysqli class to execute the query since mysql is deprecated in PHP5.
$data = mysqli_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'");
while($row = mysqli_fetch_array($data))
{
$phpClicks = $row['clicks'];
}
#If your "IF" only contains one line, you don't need brackets.
#Otherwise they are needed.
if($phpClicks == null)
die("Could not get the number of clicks of the desired username");
#This is the string PHP will send to Javascript.
$response = "Same number of clicks!";
#If phpClicks is different and has the same type as jsClicks...
if($phpClicks !== $jsClicks)
{
$response = "Number of clicks changed!";
if($jsClicks > $phpClicks)
{
#Updates the number of clicks the user has done.
$mysqli_result = mysqli_query("UPDATE customerdetails SET clicks=$jsClicks WHERE customer_username='$username';");
}
}
echo json_encode(array('response'=>$response));
?>
如果您看到您不知道它们做什么的功能或方法,请务必进行一些研究(例如:)isset
。