从 jQuery 发送一些数据,通过 setInterval 调用 PHP 中的函数
Sending some data from jQuery, calling function that is in PHP by setInterval
我想用$.post调用一个在PHP中的函数,但是每次我尝试,它只执行一次:
jQuery:
function sth()
{
$.post('index.php', { on:'1' }, function(data){});
}
setInterval(sth, 1000);
PHP:
function sthElse()
{
// Some Code
}
if($_POST['on'])
{
sthElse();
}
您的问题似乎在于将 return 结果添加到 HTML。方法如下
有父级 div,您可以在其中继续将结果列表附加到
HTML:
<div id="listOfReturns"></div>
在 JS 中,你应该按索引切片,或按分隔符拆分你的 return 字符串数据,以提取你想要的部分,然后将其作为 div 附加到上面的 div
JS:
SEPARATOR= "||";
function sth()
{
console.log('Sending post');
$.post('index.php', { on:'1' }, function(data){
console.log('Received data: '+data);
//Consider returning only necessary data from PHP
//In case, data has to processed to extract sub-portions
//Split data by a separator and then extract the right part by index
essentialData = data.split(SEPARATOR)[1];
//Slice your string by index of characters in string
//essentialData = data.slice(startIndex, endIndex);
//Finally append it to the parent div as a child div
$("#listOfReturns").append("<div>"+essentialData +"</div>")
});
}
setInterval(sth, 1000);
试试这个:
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script>
setInterval(callMe,2000);
function callMe (){
$.ajax({
url: 'test1.php',
type:'POST',
data: {on:'1'},
success: function(response){
alert(response);
}
});
}
</script>
</body>
</html>
PHP:
<?php
if(isset($_POST['on']))
echo '1';
unset($_POST['on']);
?>
我想用$.post调用一个在PHP中的函数,但是每次我尝试,它只执行一次:
jQuery:
function sth()
{
$.post('index.php', { on:'1' }, function(data){});
}
setInterval(sth, 1000);
PHP:
function sthElse()
{
// Some Code
}
if($_POST['on'])
{
sthElse();
}
您的问题似乎在于将 return 结果添加到 HTML。方法如下
有父级 div,您可以在其中继续将结果列表附加到
HTML:
<div id="listOfReturns"></div>
在 JS 中,你应该按索引切片,或按分隔符拆分你的 return 字符串数据,以提取你想要的部分,然后将其作为 div 附加到上面的 div
JS:
SEPARATOR= "||";
function sth()
{
console.log('Sending post');
$.post('index.php', { on:'1' }, function(data){
console.log('Received data: '+data);
//Consider returning only necessary data from PHP
//In case, data has to processed to extract sub-portions
//Split data by a separator and then extract the right part by index
essentialData = data.split(SEPARATOR)[1];
//Slice your string by index of characters in string
//essentialData = data.slice(startIndex, endIndex);
//Finally append it to the parent div as a child div
$("#listOfReturns").append("<div>"+essentialData +"</div>")
});
}
setInterval(sth, 1000);
试试这个:
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script>
setInterval(callMe,2000);
function callMe (){
$.ajax({
url: 'test1.php',
type:'POST',
data: {on:'1'},
success: function(response){
alert(response);
}
});
}
</script>
</body>
</html>
PHP:
<?php
if(isset($_POST['on']))
echo '1';
unset($_POST['on']);
?>