2017-05-20 7 views
0

私のコードはこのようにうまく動作します。そこ複数div sがあると$chat_idは各divに対して一意であるので、彼らは次のようになります。Ajax関数は1つの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を試しているときにそれはworkiだけです1の場合はdiv。その他div sが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のために働いています。残りは空です。私はここで何を変えるべきですか、それとも他の方法を使うべきですか?

+0

それは1のために動作します上記のコードのように 'id'を使用すると、各chat_idsにロードする場合、' id'ではなく 'class'を使用し、' .each'関数を使用して各クラスをループする必要があります –

答えて

1

一般的なJavaScript関数を1つだけ使用してください。そのJavaScript関数の内部にあるべきではありません。私はjavascriptのバニラでは非常に良好ではないですが、それはこのようなものになるだろう:あなたのPHPは、SQLやXSSの脆弱性を持たないように調整しなければならない

<!-- 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 
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 } 
} 
関連する問題