[英]Data output using Ajax with PHP
I will break this question into paragraphs for easier reference. 我将这个问题分成几段,以方便参考。
I have a script that calls a php file using Ajax; 我有一个脚本,使用Ajax调用php文件; the script is executed once a button is pressed.
一旦按下按钮,脚本就会执行。
The PHP file contains a simple code that plusses a number with 1. PHP文件包含一个简单的代码,该代码将数字加1。
<?php $response = $response + 1; echo $response; ?>
However, something goes wrong when the button is pressed multiple times. 但是,多次按下按钮时出了点问题。 I have done some research and I can conclude that there is either something wrong with the simple PHP script that I have made, or the code is only executed once per page reload.
我进行了一些研究,可以断定我编写的简单PHP脚本有问题,或者每次重新加载页面仅执行一次代码。
I read an article explaining a lot of work using Javascript if I want an Ajax command to execute multiple times during the same script but I don't see the reason that it can't execute multiple times already when the button is pressed. 我读了一篇文章,其中解释了如果我希望Ajax命令在同一脚本中执行多次,则说明了使用Javascript进行的大量工作,但是我没有看到按下按钮时该命令无法执行多次的原因。
Question: Is the PHP file "post.php" even getting executed everytime the button is pressed? 问题:每次按下按钮,PHP文件“ post.php”是否还会执行? Is it something with my PHP file?
我的PHP文件有问题吗? How can I make the script plus the number by 1 everytime the button is pressed?
每次按下按钮时,如何使脚本加上数字1? And is it because I need some extra Javascript to do that?
是因为我需要一些额外的Javascript来执行此操作?
The rest of the script is here: 脚本的其余部分在这里:
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","post.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<p>This button will execute an Ajax function</p>
<button type="button" onclick="loadXMLDoc()">Press here!</button>
<div id="myDiv"></div>
<script type="text/javascript" src="http://www.parameter.dk/counter/5b0d9873158158e08cad4c71256eb27c"></script>
</body>
If I wasn't clear enough at some point, please pick out the paragraph number and I'll deepen that part. 如果在某个时候我不够清楚,请选择段落编号,然后我将加深该部分。
In your code $response is always 1 because php by default have no state. 在您的代码中,$ response始终为1,因为php默认没有状态。 You can fix it by saving response inside a session.
您可以通过将响应保存在会话中来解决此问题。
session_start();
if (isset($_SESSION['response'])) {
$_SESSION['response'] = $_SESSION['response'] + 1;
} else {
$_SESSION['response'] = 1;
}
echo $_SESSION['response'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.