我想使用此ajax函数而不是加载方法。
目前正在使用
<div id="post_<?php echo $post_id;?>">
<script type="text/javascript" >
$(document).ready(function(){
$('#post_<?=$post_id?>').load('post.php?id=<?=$post_id?>')
});
</script>
</div>
我需要使用像这样的ajax函数更改它
<script>
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.querySelector('????').innerHTML =req.responseText;
} // how can i select the div id
}
req.open('GET','post.php?id=<?=$post_id?>',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
但是我不确定如何选择div id。
我需要它来刷新而不注意(.load重新加载整个div)。
最佳答案
尝试这个 :)
...
document.getElementById('post_<?php echo $post_id;?>').innerHTML =req.responseText;
...
在php循环中编辑make脚本
<?php foreach ($post_ids as $post_id): //I not sure how is your loop look like, this just example loop ^^"?>
<div id="post_<?php echo $post_id;?>">
<script>
function ajax<?php echo $post_id;?>(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.querySelector('#post_<?php echo $post_id;?>').innerHTML =req.responseText;
} // how can i select the div id
}
req.open('GET','post.php?id=<?=$post_id?>',true);
req.send();
}
setInterval(function(){ajax<?php echo $post_id;?>()},1000);
</script>
<?php endforeach; //end of loop example?>
或这是另一种解决方案:
<?php foreach ($post_ids as $post_id): //this is your example loop i not sure how if your loop?>
<div id="post_<?php echo $post_id;?>" class="post" data-id="<?php echo $post_id;?>"></div>
<?php endforeach; //end of loop example?>
<script>
function ajax()
{
var posts = document.getElementsByClassName('post');
for (var i = 0; i < posts.length; ++i)
{
var post = posts[i];
var post_id = post.dataset.id;
req.onreadystatechange = function()
{
if(req.readyState == 4 && req.status == 200)
{
post.innerHTML = req.responseText;
}
}
req.open('GET','post.php?id=' + post_id,true);
req.send();
}
var req = new XMLHttpRequest();
}
setInterval(function(){ajax()},1000);
</script>
我看到您的javascript循环和每秒请求数据,如果PHP循环内的脚本通常会生成每个帖子。这意味着,如果您每页显示5个帖子,则循环将运行5次。因此,上面的代码将防止此问题。
对不起,我的英语又来了。