单击html类时更新PHP变量
我需要运行PHP,特别是PHP,我不能用任何其他语言,只要点击class.URL链接 具体来说,我需要运行的PHP是:单击html类时更新PHP变量,php,javascript,jquery,Php,Javascript,Jquery,我需要运行PHP,特别是PHP,我不能用任何其他语言,只要点击class.URL链接 具体来说,我需要运行的PHP是: $list[4]+=10; 我需要它在点击时运行的链接如下所示: <a href="http://someSite'sURLHere.com" class="URL">Some site's URL</a> 我听说过jQuery的ajax()函数及其派生函数。但是我如何才能在单击.URL时更新PHP变量的值呢?首先,您的大多数问题都不可能以您希望
$list[4]+=10;
我需要它在点击时运行的链接如下所示:
<a href="http://someSite'sURLHere.com" class="URL">Some site's URL</a>
我听说过jQuery的ajax()函数及其派生函数。但是我如何才能在单击.URL时更新PHP变量的值呢?首先,您的大多数问题都不可能以您希望的方式完成。特别是在PHP中增加一个变量,这样您就有了
$list[4]+=10
。我这样说是因为当这个脚本运行时,它将不再存在,您必须从存储数据的地方(假设是DB)加载它
所以,举一个简短的例子来说明你想要实现的目标,你需要几个文件
-这是代码呈现页面及其链接的地方index.php
-单击链接时调用此函数link\u clicked.php
$(function() {
// Select all elements on the page that have 'URL' class.
var urls = $(".URL");
// Tell the elements to perform this action when they are clicked.
urls.click(function() {
// Wrap the current element with jQuery.
var $this = $(this);
// Fetch the 'href' attribute of the current link
var url = $this.attr("href");
// Make an AJAX POST request to the URL '/link_clicked.php' and we're passing
// the href of the clicked link back.
$.post("/link_clicked.php", {url: url}, function(response) {
if (!response.success)
alert("Failed to log link click.");
});
});
});
现在,我们的PHP应该如何处理这个问题
<?php
// Tell the requesting client we're responding with JSON
header("Content-Type: application/json");
// If the URL was not passed back then fail.
if (!isset($_REQUEST["url"]))
die('{"success": false}');
$url = $_REQUEST["url"];
// Assume $dbHost, $dbUser, $dbPass, and $dbDefault is defined
// elsewhere. And open an connection to a MySQL database using mysqli
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbDefault);
// Escape url for security
$url = conn->real_escape_string($url);
// Try to update the click count in the database, if this returns a
// falsy value then we assume the query failed.
if ($conn->query("UPDATE `link_clicks` SET `clicks` = `clicks` + 1 WHERE url = '$url';"))
echo '{"success": true}';
else
echo '{"success": false}';
// Close the connection.
$conn->close();
// end link_clicked.php
这没有任何意义。PHP在呈现页面之前在服务器上运行。您的变量不存在。您的问题含糊不清,涉及的主题太多。你没有努力学习,也没有自己去寻找答案。我听说jQuery ajax()函数的含义是什么?转到jquery网站并阅读相关内容。@SLaks但有没有办法在页面呈现后,在单击页面时更新存储在内存中的变量?@mastaBlasta我确实尝试过阅读有关ajax函数的内容,但不知道如何使用它在单击时更新PHP中的数组值。非常感谢。我会从中学到很多。