我的代码以这种方式工作得很好。有多个 div
,并且 $chat_id
对于每个 div
都是唯一的,因此它们看起来像:
<div id=chatbox_1>...
<div id=chatbox_2>...
...etc.
index.php:
<div id="chatbox_<?php echo $chat_id; ?>" >
<script type="text/javascript" >
$(document).ready(function(){
$('#chatbox_<?=$chat_id?>').load('chat.php?id=<?=$chat_id?>')
});
</script>
</div>
chat.php:
<?php
include 'db.php';
if (isset($_GET['id'])){
$c_id = $_GET['id'];
}
$query = "SELECT * FROM `chat` where `chat_id`='$c_id'";
$run = $con->query($query);
while($row = $run->fetch_array()){ ?>
<div id="chat_data">
<span style="color:brown;"><?php echo $row['msg']; ?></span>
</div>
<?php } ?>
问题是当我尝试这个ajax时它只适用于一个div
。其他 div
未加载 chat.php
<div id="chatbox_<?php echo $chat_id; ?>" >
<script type="text/javascript" >
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.getElementById('chatbox_<?=$chat_id?>').innerHTML = req.responseText;
}
}
req.open('GET','chat.php?id=<?=$chat_id?>',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
</div>
.load
工作正常,但此 ajax 函数仅适用于一个 div
。其余的都是空的。我应该在这里更改什么,还是应该使用其他方法?
最佳答案
您应该只有一个通用 JavaScript 函数,并且它不应该位于它所作用的 div
内。我不太擅长普通的 javascript,但它会是这样的:
<!-- You just load the id into the ajax function -->
<div id="chatbox_<?php echo $chat_id ?>" onload="setInterval(function(){ajax('<?php echo $chat_id ?>')},1000);"></div>
<!-- You only have one function and it is all javascript-based -->
<script type="text/javascript" >
function ajax(id)
{
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.getElementById('chatbox_'+id).innerHTML = req.responseText;
}
}
req.open('GET','chat.php?id='+id,true);
req.send();
}
</script>
应该调整你的 PHP,使其不存在此类 SQL 和 XSS 漏洞:
<?php
include('db.php');
# Check if the GET value is numeric (presuming it is supposed to be)
if(isset($_GET['id']) && is_numeric($_GET['id'])){
$c_id = $_GET['id'];
$query = "SELECT * FROM `chat` where `chat_id`='{$c_id}'";
$run = $con->query($query);
while($row = $run->fetch_array()){ ?>
<div id="chat_data">
<!-- You need to sanitize your output or you will have people taking advantage
of javascript hackery -->
<span style="color:brown;"><?php echo htmlspecialchars($row['msg'],ENT_QUOTES) ?></span>
</div>
<?php }
}
关于javascript - Ajax功能仅适用于一个div,不适用于其他div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44081371/