我运行的网站现在提供通知功能,我想运行一个脚本,每60秒检查一次新消息。我需要做的是通过脚本传递use id然后创建一个警报(现在我已经使用了基本的浏览器警报),但我的代码似乎没有工作。这是我到目前为止的代码:
JQuery
<script type="text/javascript">
$(document).ready(function()
{
var check;
var yourid = <?php echo json_encode($yourid); ?>;
function checkForMessages() {
jQuery.ajax({
type: 'POST',
url: 'php/check-messages.php',
data: 'id='+ yourid,
cache: false,
success: function(response){
if(response = 1){
clearInterval(check);
alert("You have mail!");
}
else {}
}
});
}
check = setInterval(checkForMessages, 60000);
};
</script>
Check Messages PHP
<?php
include("settings.php");
$id= mysqli_real_escape_string($con, $_REQUEST["id"]);
$check_messages_sql = "SELECT * FROM notes WHERE recipient = '$yourid' AND seen = '0'";
$check_messages_res = mysqli_query($con, $check_messages_sql);
if(mysqli_affected_rows($con)>0){
echo "1";
}
?>
答案 0 :(得分:1)
怎么样?
function checkForMessages(yourid) {
jQuery.ajax({
type: 'POST',
url: 'php/check-messages.php',
data: 'id='+ yourid,
cache: false,
success: function(response){
if(response = 1){
clearInterval(check);
alert("You have mail!");
}
else {}
}
});
}
check = setInterval(checkForMessages(yourid), 60000);
答案 1 :(得分:0)
你可以使你的函数递归,并添加60秒的延迟:
function checkForMessages() {
var dataObj = {};
dataObj['id']= yourid;
jQuery.ajax({
type: 'POST',
url: 'php/check-messages.php',
data: dataObj,
cache: false,
success: function(response){
if(response == 1){
clearInterval(check);
alert("You have mail!");
}
else {}
}
});
setTimeout(
function()
{
checkForMessages();
}, 1000);
}
这样,您的功能将每1000毫秒重新启动一次。
答案 2 :(得分:0)
尝试将检查用作if(response == 1)
并将超时设置如下....
setTimeout(function() {checkForMessages();}, 2000);