如何使用包含php的javascript添加表单元素?

如何使用包含php的javascript添加表单元素?,javascript,php,Javascript,Php,这是我的代码: Category: <select name='category'> <?php $query = "SELECT * FROM `categories`"; $result = mysql_query($query); if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_row($result)) { echo "<option name={

这是我的代码:

Category:
<select name='category'>
<?php
    $query = "SELECT * FROM `categories`";
    $result = mysql_query($query);
    if (mysql_num_rows($result) > 0) {
    while($row = mysql_fetch_row($result)) {
    echo "<option name={$row[0]} value={$row[1]}>{$row[1]}</option>";
}} ?>
</select> <br><br>

Quantity:
<input type='text' name='quantity' onkeypress="return isNumberKey(event)"><br><br>

Price:
<input type='text' name='price' onkeypress="return isNumberKey(event)"><br><br>
<a href='#' onclick="addformfield()">Insert another item</a>
<input type='submit' value='Submit'>
当用户单击Insert另一个项目时,我想再次使用Javascript添加如上所示的类别、数量和价格


请帮忙

只是一个不需要AJAX请求的快速解决方案

<?php
$categories = array();
$query = "SELECT * FROM `categories`";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
    while($row = mysql_fetch_row($result)) {
        $categories[$row[0]] = $row[1];
    }
}
?>

<div id="groups"></div>
<a href='#' id="insert-another-item">Insert another item</a>

<script>    
var categories = <?= json_encode($categories) ?>,
    groupId = 0;

$(function() {
    insertGroup();
    $('#insert-another-item').on('click', function() {
        insertGroup();
        return false;
    });     
}); 

function insertGroup() {
    group = '<div class="group">' 
              + '<select name="groups[' + groupId + '][category]"></select>'
              + '<input type="text" name="groups[' + groupId + '][quantity]">'
              + '<input type="text" name="groups[' + groupId + '][price]">'
          + '</div>';

    $('#groups').append(group);

    $.each(categories, function(key, value) {
        $('select[name="groups[' + groupId + '][category]"]').append('<option value="' + key + '">' + value + '</option>');
    });

    groupId++;
}

您没有提到当前代码有什么问题,那么您尝试了什么?@meda我无法理解如何使用javascript从数据库中获取项并插入select选项。您的表单元素将不包含php,在呈现页面之后,php将已经运行,没有其他处理php的方法。您不能在客户端添加php元素并期望它工作。它们是两个独立的概念,彼此并不真正了解。您需要使用AJAX从服务器获取所需的信息,即您要放置的php,然后在客户端插入适当的html元素。嘿,谢谢您的回复。但我不能让它工作。它获取数据,但单击链接后,元素不会附加到组中。是否包含jQuery?无论它如何工作,您都可以在此处查看: