2015-06-27 55 views
0

我正在製作一個帶有向上和向下按鈕的圖片庫,數組$ imageids包含所有圖片ID。我想如下與 JavaScript來訪問這些值,在PHP數組中放入一個JavaScript變量

PHP:

require"./connect.php"; 
$imgquery = mysql_query("SELECT * FROM press INNER JOIN subscriptions ON  press.userid=subscriptions.to_u WHERE subscriptions.from_u='30' ORDER BY press.id DESC "); 
$countrow = mysql_num_rows($imgquery); 
$imageids = array(); 
while($fimgq = mysql_fetch_assoc($imgq)) { 
    $imgid = $fimgq['id']; 
    array_push($imageids,$imgid); 
} 

的JavaScript:

$(document).ready(function() { 
    var i = -1; 
    var cr = <?php echo $countrow ?>; 
    $('#down').click(function() { 
     if (i < cr-1) { 
      i = i + 1; 
      var ard = <?php echo $imageids[i]?>; 
      alert(ard); 
     } 
    }); 
    $('#up').click(function() { 
     if(i>0) { 
      i = i - 1; 
      var aru = <?php echo $imageids[i]?>; 
      alert(aru); 
     } 
    }); 
}); 

我想通過把一個javascript變量i得到$imageids元素裏面$imageids[]陣列,就像

var ard = <?php echo $imageids[i]?>; 
alert(ard); // Which doesn't work 
+3

PHP生成javascript。它在頁面加載後不可用。將PHP數組輸出到JavaScript,然後在JS中遍歷它。 – chris85

+1

@ chris85是對的。 PHP是服務器端,JavaScript(在這種情況下)是客戶端。一旦運行JavaScript,PHP已經呈現爲HTML。並完成對服務器的請求。 – Khalos

回答

0

As @ chris85和@Khalos在註釋中指出,一旦JavaScript運行,PHP變量全部死掉,因此您需要將所有ID輸出到JavaScript數組中。它會吸引像這樣的東西:

$(document).ready(function(){ 

    var i=-1; 
    var cr= <?php echo $countrow ?>; 

    //Save all the ID:s to a JS variable so they can be used later. 
    var imageids = [<?php echo implode(',', $imageids); ?>]; 

    $('#down').click(function(){ 
    if(i<cr-1) { 
     i=i+1; 
     alert(imageids[i]); //This uses the JS variable imageids, not the dead PHP one. 
    } 
    });  

    $('#up').click(function(){ 
    if(i>0) { 
     i=i-1; 
     alert(imageids[i]); //Same as above. 
    } 
    }); 

}); 
相關問題