我想使用这个ajax函数而不是load方法。
目前正在使用
<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)。
答案 0 :(得分:0)
试试这个:)
...
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次。所以上面的代码将防止这个问题。
对不起我的英语。
答案 1 :(得分:0)
您可以使用您的php解释器
document.querySelector('#post_<?php echo $post_id;?>').innerHTML =req.responseText;
答案 2 :(得分:0)
使用getElementById()
<div id="post_<?php echo $post_id;?>">
<script>
function ajax() {
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
document.getElementById('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()
}, 1000);
</script>