【问题标题】:update PHP variable on click of html class [closed]点击html类更新PHP变量[关闭]
【发布时间】:2013-06-03 14:44:08
【问题描述】:

我需要运行 PHP,特别是 PHP,我无法在任何其他语言中运行,单击带有类 .URL 的链接

具体我需要运行的 PHP 是这样的:

$list[4]+=10;

我需要它在点击时运行的链接如下所示:

<a href="http://someSite'sURLHere.com" class="URL">Some site's URL</a>

我听说过 jQuery 的 ajax() 函数及其衍生物。但是如何在点击 .URL 时更新 PHP 变量的值?

【问题讨论】:

  • 这没有任何意义。 PHP 在服务器上运行,页面被渲染。您的变量不存在。
  • 您的问题含糊不清,涉及的主题太多。你没有付出任何努力去学习和自己寻找答案。 i have heard about jQuery ajax() function 是什么意思?转到 jquery 网站并阅读它。
  • @SLaks 但是有没有办法在页面呈现后更新存储在内存中的变量?
  • @mastaBlasta 我确实尝试阅读有关 ajax 函数的内容,但无法弄清楚如何使用它在点击时更新 PHP 中数组的值。

标签: php javascript jquery


【解决方案1】:

首先,您的大部分问题都无法按照您希望的方式完成。专门增加 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

此示例本质上过于简单,并使用了一些不推荐的方法来执行任务。我将根据您的要求找到如何正确执行此操作。

【讨论】:

  • 非常感谢。我会从中学到很多东西。
猜你喜欢
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 2014-03-18
  • 2015-02-02
  • 1970-01-01
  • 2012-10-29
  • 2021-10-06
  • 2013-02-17
相关资源
最近更新 更多