使用onclick函数增加PHP变量的值

时间:2016-03-11 17:51:56

标签: javascript php jquery variables

我有一个变量$count = 10;,每次用户点击<a id="load-more" href="#">Load more</a>

时我想增加10

我尝试使用onclick,变量方程式和函数来设置它,但我似乎无法让它增加。

最终,我希望每次用户点击时$count = 10;增加到$count = 20;等等。

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你正在寻找一个使用AJAX的解决方案。像这样:

在客户端:

$('#load-more').click(function () {
  $.ajax({
    type: 'POST',
    url: "http://example.com/stuff.php",
    async: true,
    success: function(data) {
      // Success! Do something with `data` here:
    },
    error: function (jqXHR, textStatus, errorThrown) {
      // Error! You should probably display an error message here:
    }
  })
})

在服务器上(stuff.php):

<?php
  $value = retrieveValue(); // Replace this with whatever means you are using to get the persisted value.
  $value += 10; // Increment the value by 10 each time.
  saveValue($value); // Replace this with whatever means you are using to save the persisted value.
?>

请记住,为了保持每个请求的值递增,您必须通过某种方式(数据库,会话,文件等)将值保存在PHP中。

您还需要在HTML文件中加载JQuery库以使用上述JavaScript代码。

答案 1 :(得分:0)

不可能通过JavaScript(客户端)更改PHP变量的值(服务器端)。 您可以定义JavaScript变量并使用PHP对其进行初始化。但之后,您只能使用JavaScript变量。

<script>
var jsVar = <?php echo $phpVar; ?>;
jsVar++;
</script>

这就是方法。有关更多信息,上面的代码是将PHP变量值发送到JavaScript(相反,不可能)。

  • 您还可以使用AJAX命令将JavaScript变量的值发送到PHP脚本。

如果你想使用AJAX命令,你可以通过纯JavaScript或使用jQuery或其他库来实现。 jQuery使用更容易,但您需要加载库。我更喜欢纯JavaScript AJAX。这是一个例子:

<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', 'php_script.php');
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        // do something
    }
};
xhr.send('value=' + jsVar);
</script>

您可以在php_script.php文件中使用值$_POST['value']

答案 2 :(得分:-1)

在这里。

<input type="number" value="10" id="data"> <a id="load-more" href="#" onClick="increment()">Load more</a>

<script> function increment(){ var count = parseInt(document.getElementById("data").value); count = count+=10; document.getElementById("data").value = count $.post('backend.php?count='+$("#data").val(),function(val){//alert}); } </script>