2013-08-22 79 views
-1

我試圖從數據庫打印文本框和下拉列表。我打印文本框並根據給定的輸入下拉菜單。如何使用JavaScript在循環中打印PHP下拉列表

例如:假設我給出的輸入爲4.爲此,它將創建四個文本框和下拉菜單。

但是我在PHP中有下拉代碼,所以現在我想用JavaScript打印循環中的PHP下拉菜單。我怎樣才能做到這一點?

JavaScript代碼:

function create(param) { 
    'use strict'; 

    var i, target = document.getElementById('screens'); 
    target.innerHTML = ''; 

    for(i = 0; i < param; i += 1) { 
     target.innerHTML +='</br>'; 
     target.innerHTML +='New Movie '+i+' '; 
     target.innerHTML += '<input type="text" name="Fname">'; 
     target.innerHTML +=' '+'Language '+' '; 
     target.innerHTML += '<input type="text" name="timings">'; 
     target.innerHTML +='</br>'; 
     target.innerHTML +='</br>'; 
    } 
} 

PHP下拉:

<?php 
    try { 
     $dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger'); 
    } 
    catch (PDOException $e) { 
     echo 'Connection failed: ' . $e->getMessage(); 
    } 

    $sql = "SELECT language FROM languages;"; 

    $sth = $dbh->prepare($sql); 
    $sth->execute(); 

    echo "<select name='language' id='course'>"; 
    echo "<option>----Select Language----</option>"; 
    while($row = $sth->fetch(PDO::FETCH_ASSOC)) { 
     echo "<option value='" . $row['language'] ."'>" . $row['language']. "</option>"; 
    } 
    echo "</select>"; 
?> 

在地方的

target.innerHTML += '<input type="text" name="timings">'; 

我應該得到一個PHP下拉列表,而不是一個文本框。

+1

而不是從服務器端打印HTML的,我會建議發送它作爲一個JSON字符串 - >解析它在客戶端 - >創建html – Johan

回答

1

最簡單的辦法,因爲你有兩個代碼....

function create(param) { 
    'use strict'; 

    var i, target = document.getElementById('screens'); 
    target.innerHTML = ''; 
<?php 
     try { 
      $dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger'); 
     } catch (PDOException $e) { 
      echo 'Connection failed: ' . $e->getMessage(); 
     } 

     $sql = 'SELECT language FROM languages;'; 

     $sth = $dbh->prepare($sql); 
     $sth->execute(); 
     $combo = "<select name='language' id='course'>"; 
     $combo .= "<option>----Select Language----</option>"; 
     while($row = $sth->fetch(PDO::FETCH_ASSOC)) { 
      $combo .= "<option value='" . $row['language'] ."'>" . $row['language']. "</option>"; 
     } 
     $combo .= "</select>"; 
?> 
    for(i = 0; i < param; i += 1) { 
     target.innerHTML +='</br>'; 
     target.innerHTML +='New Movie '+i+' '; 
     target.innerHTML += '<input type="text" name="Fname">'; 
     target.innerHTML +=' '+'Language '+' '; 
     target.innerHTML += "<?php echo $combo; ?>"; 
     target.innerHTML +='</br>'; 
     target.innerHTML +='</br>'; 
    } 
}