使用 AJAX 和 ORACLE 以及不使用 php 填充下拉列表(选择 )

Popoulate dropdown (select ) using AJAX and ORACLE and JSP without using php

本文关键字:填充 php 下拉列表 选择 AJAX ORACLE 使用      更新时间:2023-09-26

我需要动态检索下拉菜单的选项,但不要使用 php 脚本。仅使用 jsp/jquery/ajax 和数据库连接,我需要根据第一个下拉菜单中选择的值自动填充选项。

下面的html页面有两个选择下拉列表,在选择品牌时,我们需要自动填充id。

<html>
 <head>
 <title>PHP MySQL Insert Tutorial</title>
 <script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
 </head>
 <body>
 <select id='brand'>
 <option value='nokia'>nokia</option>
 <option value='motorola'>motorola</option>
 <option value='samsung'>samsung</option>
 </select>
 <select id='item'>
 </select>
 <script src='fetch.js'></script>
 </body>
</html>

下面是一个java脚本,它将一个php文件作为数据库连接的输入

  $.getJSON(
     'fetch.php',
     'brand='+$('#brand').val(),
     function(result){
     $('#item').empty();
     $.each(result.result, function(){
     $('#item').append('<option>'+this['item']+'</option>');
     });
     }
     );
    });

下面是 php 脚本

    <?php
     define('HOST','localhost');
     define('USERNAME', 'root');
     define('PASSWORD','');
     define('DB','myDatabase');
     $con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
     $brand = $_GET['brand'];
     $sql = "select item from products where brand='$brand'";
     $res = mysqli_query($con,$sql);
     $result = array();
     while($row = mysqli_fetch_array($res)){
     array_push($result, 
     array('item'=>$row[0]));
     }
     echo json_encode(array('result'=>$result));
     mysqli_close($con);
    ?>

我需要使用Oracle数据库

使用 servlet 而不是 JSP。在 servlet 的方法doGet()中,编写以下内容:

...
String brand = request.getParameter("brand");
List<String> items = new ArrayList<String>();
// here access to the DAO layer and retrieve the information
String json = new Gson().toJson(items);
response.setContentType("application/json");
response.getWriter().write(json);
...

在 JavaScript 代码中,跟踪第一个组合框中的更改,并相应地更改第二个组合框中的内容:

...
$('#brand').change(function(event) {
        var brand = $("select#brand").val();
        $.post('YourServletHere', {
                brand: brand
        }, function(response) {
              var item = $('#item');
              item.empty();
              $.each(response, function(idx, value) {
                 $('<option>').val(value).text(value).appendTo(item);
              });
        });
    });
});
...