首先,您的大部分问题都无法按照您希望的方式完成。专门增加 PHP 中的变量,使您拥有$list[4] += 10。我这样说是因为当这个脚本运行时它不再存在,你必须从你碰巧存储数据的地方加载它(假设是一个数据库)。
因此,您需要几个文件来说明您要实现的目标的简短示例。
-
index.php - 这是您的代码出现的地方,它会呈现带有链接的页面。
-
link_clicked.php - 点击链接时调用。
您将在代码中添加需要这个基本的 Javascript(它使用 jQuery,因为您在问题中提到了它)。我已经把这个 sn-p 分成了很多部分,这不是你通常写的或看到写的 jQuery 来解释发生了什么。
$(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
此示例本质上过于简单,并使用了一些不推荐的方法来执行任务。我将根据您的要求找到如何正确执行此操作。