我正在尝试创建一个简单的webapp类的东西,它将在按钮单击时向我的客户发送推送通知。这是我创建的示例页面
我有一个名为sendPush.php
的文件
在按钮上单击我要发送一个推送通知,该通知将作为
Notifications sent:
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
我想发送通知给所有147个用户。现在,这里是我的按钮单击的PHP代码
<script type="text/javascript">
function sendNotif()
{
alert('ok');
}
</script>
<div class="content">
<input type="button" value="Click to Send" onClick="sendNotif();">
<br />
<br />
<label for="push">Notifications sent: </label>
</div>
我在这里面临的问题是,我在名为sendNotification()的同一应用中具有php函数,该函数将发送通知并回显结果。但是我不确定如何在javascript函数内部的javascript中循环此php函数
function sendNotif()
{
// LOOP HERE
}
如果
$clients
是我的客户列表,我如何在与sendNotification($client)
相同的页面中使用php函数将notif循环发送给所有人改性
<script type="text/javascript">
var lastIdCount = 0;
function sendNotif()
{
var clients = "<?php echo $clients; ?>";
var getPath = "push.php?clientId=".concat(clients['lastIdCount']);
$.ajax({
type: "POST",
url: getPath,
task: "save",
data: {
ajax: "true",
},
dataType : 'json'
}).done(function( msg )
{
alert('ok');
if( msg.status=="1")
{
alert('okasdf');
lastIdCount++;
sendNotif();
}
else
{
alert("Error : "+msg.error);
}
});
}
</script>
在push.php中
样品
$resp = array();
$resp['error'] = 'Invalid Request';
$resp['status'] = '0';
$resp['data'] = '0';
最佳答案
您可以首先尝试获取要发送通知的所有客户端,并将它们的ID用作setInterval或setTimeout函数,它们会重复您的查询。也许你应该
get_clients.php
<?php
$clients_array = array(1,2,6,15,29); /// let's say ID's you got from SQL or w/e you need.
echo json_encode($clients_array); // [1,2,6,15,29]
?>
send_for_client.php
<?php
$id = isset($_POST['id'])?$_POST['id']:false;
if($id){
// do some code you need
echo "Notification sent for id: ".$id;
}
?>
index.html
...
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(window).load(function(){
$("#send").click(function(){
$.post('get_clients.php',{},function(cid){
obj = JSON.parse(cid);
var cids = obj;
/// cids is array of clients. so, you can do like:
var i = 0;
var interval = setInterval(function(){
if(cids.length > i){
$.post('send_for_client.php',{id:cids[i]},function(resp){
$("#result").append(resp+"<br />");
i++;
});
} else {
clearInterval(interval);
}
},100);
});
});
});
</script>
</head>
<body>
<input id="send" type="submit" name="button" value="Send notifications" />
<div id="result">
</div>
</body>
...
我没有测试过这种想法,但是它应该可以工作,或者只是表明您可以如何尝试解决问题的想法。请记住,此代码可能有错误,所以..不要懒惰地检查它们,甚至不要复制/粘贴:)
我希望它能有所帮助。
关于javascript - 创建一个循环来调用php函数,并在javascript的同一html页面上从该函数回显,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25092612/