Javascript变量-AJAX-发送到服务器而无需等待答案

时间:2019-10-08 15:27:39

标签: javascript php ajax

我的点击计数器不向服务器发送变量。

我试图找到如何创建示例,但是无论我怎样尝试,都没有尝试将数据发送到server.AJAX应该是最好的选择,但是我做错了。我也尝试了window.location.href javascript,但是这将我重定向到其他页面,我想在当前srcipt中继续。

court1.js:


var button = document.getElementById("clickme"),
  count = 0;
button.onclick = function() {
  count += 1;
  button.innerHTML = "result: " + count;
$.ajax({
    type: 'POST',
    url: 'count.php',
    data:+count,
});
};

index.html


<html>

<head>
  <meta charset="UTF-8">
  <title></title>
<style>
body {
  margin: 0;
  padding: 0;
  font-family: "Lato", sans-serif;
  font-size: 20pt;
  font-weight: normal;
  background: lightblue; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(
    -90deg,
    lightblue,
    black
  ); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(
    -90deg,
    lightblue,
    black
  ); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(
    -90deg,
    lightblue,
    black
  ); /* For Firefox 3.6 to 15 */
  background: linear-gradient(-90deg, lightblue, black); /* Standard syntax */
}

.main {
  margin: 100px auto;
  text-align: center;
}

button {
  padding: 20px;
  background: transparent;
  text-shadow: 1px 1px 1px #202020;
  font-family: "Lato", sans-serif;
  font-size: 18pt;
  border: 1px solid lightblue;
  color: lightblue;
}
</style>
</head>

<body>
  <div class="main">

    <h3>court 1</h3>
    <button id="clickme">click here</button>


  </div>
<script src="court1.js"></script>
</body>

</html>

计数器工作正常。.从0开始刷新后。 但是我没有看到任何将变量发送到服务器的尝试。 chrome中的调试模式未显示任何活动。

我需要在每次触摸(单击)后将新值从变量$ count发送到服务器。柜台必须继续工作,不得打扰。我们正在谈论每秒点击几下。
我想向php脚本发送新值,或者我也愿意通过UDP数据包向服务器发送新值并通过syslog-ng在服务器上收集数据。

优先级是客户端上最小的资源负载。 谢谢您的帮助

2 个答案:

答案 0 :(得分:0)

主要问题是HTML代码中没有加载的jQuery:

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

这是主要原因,为什么未激活ajax。

答案 1 :(得分:-1)

正确的Ajax部分,其发送变量为ULR / court1.php?“变量”

$.ajax({
    type: 'POST',
    url: 'court1.php?' + count,
});