2016-02-17 109 views
1

我在函數內循環時遇到了麻煩。這不起作用,我想因爲我的循環,我需要一些幫助糾正,請。 :)和問題如何循環使用Javascript函數?

的建議,下面是我做了什麼:

<script> 
     function getImage1(str) { 


     if (window.XMLHttpRequest) { 
      // code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp=new XMLHttpRequest(); 
     } else { // code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     xmlhttp.onreadystatechange=function() { 
     for (i = 0; i < xmlhttp.length; i++) { 
      if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
      document.getElementById("result1").innerHTML=xmlhttp.responseText; 

      } 
     } 
     xmlhttp.open("GET","getImage.php?no="+str,true); 
     xmlhttp.send(); 
     } 
     } 

    </script> 

這裏是我的PHP:

<select onchange="getImage1(this.value)" name="<?php echo $rowasa['pos_name'] ?>" style="height: 47px;"> 
     <option value='0' >Pls. Select <?php echo $rowasa['pos_name'] ?></option> 
     <?php 
     include('connection/connect.php'); 
     $dsds=$rowasa['posid']; 
     $YearNow=Date('Y'); 
      $results = $db->prepare("SELECT * FROM candidates,student,school_year,partylist where student.idno = candidates.idno AND school_year.syearid = candidates.syearid AND posid =:a AND candidates.partyid = partylist.partyid "); 

      $results->bindParam(':a', $dsds); 
      $results->execute(); 
      while($rows = $results->fetch()){ 
          ?><!---$rows['candid'] . "," .--> 
        <option style="padding: 35px 50px 35px 80px; background:url('admin/candidates/images/<?php echo $rows['image']; ?>') no-repeat scroll 5px 7px/70px auto rgba(0, 0, 0, 0);" 

       value="<?php echo $rows['candid'] . "-" ."&nbsp". $rows['lastname'] .",". "&nbsp". $rows['firstname'] ?>"> <?php echo $rows['lastname'] ?>, 
        <?php echo $rows['firstname'] ?> 

       - <?php 
         echo $rows['party_name']?></option> 

       <?php 

      } 

     ?> 
      </select> 
      <div class="12u$"><span id="result1"> 
+0

你在哪裏'echo'來標記/ – Rayon

+0

我覺得很多問題來縮小一次,但你你循環 –

+0

也沒有看到任何理由環路輸出相同的responseText前應檢查的readyState和狀態。一旦它返回,它不會改變,除非再次請求 –

回答

0

你並不需要循環theough XHR對象。只要在狀態改變時得到你的迴應。

<script> 
     function getImage1(str) { 


     if (window.XMLHttpRequest) { 
      // code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp=new XMLHttpRequest(); 
     } else { // code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     xmlhttp.onreadystatechange=function() {   
      if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
      document.getElementById("result1").innerHTML=xmlhttp.responseText;  
      } 

     xmlhttp.open("GET","getImage.php?no="+str,true); 
     xmlhttp.send(); 
     } 
     } 

    </script>