使用AJAX使用OPTGROUP和OPTION值填充SELECT

时间:2016-03-16 08:41:48

标签: javascript php jquery ajax

我有一点简单的PHP / Ajax / jQuery工作,这样当我在第一个SELECT中选择一个值时,第二个SELECT的内容就会改变。

HTML

<select class='form-control' id='cat_parent' name='cat_parent'>
    <option value=''>Select Parent</option>
    <option value='1'>Oracle</option>
    <option value='6'>SQL</option>
</select>

<select class='form-control' id='cat_id' name='cat_id'>
</select>

jQuery的:

$(document).ready(function() {
    $('#cat_parent').change(function() {
        var currentValue = $(this).val();
        // Populate Categories once select Parent
        $.get("../ajax/ajax-cats-from-parent.php", {'cat_parent': currentValue}, function(data) {
            var cat_id = $.parseJSON(data);
            $('#cat_id').empty();
            for (var i = 0; i < cat_id.length; i++) {
                var regionOption = '<option value="'+cat_id[i]['id']+'">';
                regionOption += cat_id[i]['label'];
                regionOption += '</option>';
                $('#cat_id').append(regionOption);
            }
        });

    });
});

PHP(ajax-cats-from-parent.php)

 $sql = "SELECT cats.fld_label
              , cats.fld_id
           FROM tbl_b_cats cats
          WHERE cats.fld_parent = ? 
       ORDER BY cats.fld_label";

$stmt = $conn->stmt_init();

if (!$stmt->prepare($sql)) {
    throw new Exception("Error preparing statement: $stmt->error, SQL query: $sql");
}

if (!$stmt->bind_param('s', $_GET['cat_parent'])) {
    throw new Exception("Error binding parameter: $stmt->error");
}

$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows == 0) {
    header('HTTP/1.0 404 Not Found');
    exit;
} else {

    $AjaxCatsFromParent = array();

    $stmt->bind_result($fld_label, $fld_id);

    while ($stmt->fetch()) {
        $AjaxCatsFromParent []= [
            'id'    => $fld_id,
            'label' => $fld_label
        ];
    }

    echo json_encode($AjaxCatsFromParent);

}
$stmt->free_result();
$stmt->close();

$conn -> close();

一切正常。

我试图填充另一个SELECT,同样基于在第一个SELECT菜单中选择一个值(ID cat_parent)。

这样,对于新帖子,我可以指定一个父帖子。

我遇到的麻烦是SELECT为每个类别都有一个OPTGROUP标签,然后在OPTGROUP中列出了该类别的帖子。

获取帖子的SQL是:

$query = "SELECT fld_id fld_id2
               , fld_title fld_title2 
            FROM tbl_c_posts 
           WHERE fld_catid = ? 
        ORDER BY fld_title";

哪里?是分配帖子的类别的ID。

我希望SELECT看起来像这样:

<select class='form-control' id='parent_cat_id' name='parent_cat_id'>
    <option value=''>Select Parent Post</option>
    <optgroup label='Accounts Payable'>
            <option value='88'>a</option>
            <option value='1'>AP - Invoices</option>
            <option value='79'>AP - Supplier Reports</option>
    </optgroup>
    <optgroup label='Accounts Receivable'>
            <option value='2'>AR - Customers</option>
            <option value='3'>AR - Interface Lines</option>
            <option value='4'>AR - Transactions</option>
    </optgroup>
    <optgroup label='BLOB'>
            <option value='87'>s</option>
            <option value='86'>sadsadsad</option>
    </optgroup>
</select>

因此我遇到的问题是PHP需要输出:

  1. 类别的循环(输出OPTGROUP标签)
  2. 对于每个类别,分配给该类别的帖子循环(以输出OPTION值)
  3. 但是,据我所知,PHP代码只能输出一个数组?

    我到目前为止:

    // SQL FOR THE OPTGROUP LABELS ############################################
    
     $sql = "SELECT cats.fld_label
                  , cats.fld_id
               FROM tbl_b_cats cats
              WHERE cats.fld_parent = ?
           ORDER BY cats.fld_label";
    
    $stmt = $conn->stmt_init();
    
    if (!$stmt->prepare($sql)) {
        throw new Exception("Error preparing statement: $stmt->error, SQL query: $sql");
    }
    
    if (!$stmt->bind_param('s', $_GET['cat_parent'])) {
        throw new Exception("Error binding parameter: $stmt->error");
    }
    
    $stmt->execute();
    $stmt->store_result();
    
    if ($stmt->num_rows == 0) {
        header('HTTP/1.0 404 Not Found');
        exit;
    } else {
    
        // array for OPTGROUPS
        $AjaxOptGpLabel = array();
    
        $stmt->bind_result($fld_label, $fld_id);
    
        while ($stmt->fetch()) {
            $AjaxOptGpLabel []= [
                'label' => $fld_label
            ];
    
            // sub-select for the posts assigned to the category
            $query = "SELECT fld_id fld_id2
                           , fld_title fld_title2 
                        FROM tbl_c_posts 
                       WHERE fld_catid = ? 
                    ORDER BY fld_title";
    
            $stmt2 = $conn->stmt_init();
    
            if (!$stmt2->prepare($query)) {
                throw new Exception("Error preparing statement: $stmt2->error, SQL query: $query");
            }
    
            if (!$stmt2->bind_param('s', $fld_id)) {
                throw new Exception("Error binding parameter: $stmt2->error");
            }
    
            $stmt2->execute();
            $stmt2->store_result();
    
            if ($stmt2->num_rows > 0){
    
                // array for the posts
                $AjaxOptGpPosts = array();
    
                /* get results */
                $stmt2->bind_result($fld_id2, $fld_title2);
    
                while ($stmt2->fetch()) {
    
                    $AjaxOptGpPosts []= [
                        'id'    => $fld_id2,
                        'label' => $fld_title2
                    ];
    
                }
    
            }
    
            /* tidy up */
            $stmt2->free_result();
            $stmt2->close();
    
        }
    
        echo json_encode($AjaxOptGpLabel);
    
    }
    /* free and close */
    $stmt->free_result();
    $stmt->close();
    
    $conn -> close();
    

    因此,这种工作与PHP生成一个&#34; AjaxOptGpPosts&#34;包含每个类别的帖子的数组,但是呢?

    1. 如何将其输入到PHP的输出中,因为它目前只通过以下方式返回OPTGROUPS的数组:

      echo json_encode($ AjaxOptGpLabel);

    2. 我如何修改jQuery以在循环中循环以填充OPTGROUPS和OPTION元素?

    3. 谢谢!

0 个答案:

没有答案
相关问题