通过 AJAX 填充 HTML 文件的选择元素

问题描述 投票:0回答:1

我有点卡住了,我想把这个PHP列表。

<?php
   include 'conexion.php';
   $queri= mysqli_query($est, "SELECT * FROM objeto_gasto order by codigo" );
   ?>

   <!DOCTYPE html>
   <html lang="en">
   <head>
  
    <title>lista objetos</title>
   </head>
   <body>
     <div>
        <select name="objetos">
        <?php 
        while($datos_obj= mysqli_fetch_array($queri))
        {
            ?>
        <option value="<?php echo $datos_obj['codigo'] ?>"><?php echo $datos_obj['detalle']?>     </option>

        <?php
        }
        
        
        ?>
        </select>
    </div>

与数据库的连接工作正常,并且它还在所示代码的选择中显示了列表,但现在我想将其放入我的 HTML 页面中,而不将 HTML 文件更改为 PHP。

此外,学习和提高我的编程技能并将其付诸实践。

php html ajax
1个回答
1
投票

如果我理解正确的话,你需要这个(不完整,抱歉)
使用 JavaScript 和 Ajax

newphp.php

<?php

include_once 'config.php';

$select = $connection->prepare("SELECT username FROM table");
$select->execute();
$select = $select->fetchAll();

foreach ($select as $row) {
    echo $row['username'] . ',';
}
?>



newhtml.html

<!DOCTYPE html>
<html lang="en">
    <body>

        <div id="demo"></div>

        <script>
            function receive() {
                const http = new XMLHttpRequest();
                http.onload = function () {
                    var splits = this.responseText.split(','), select = '';
                    for (let i = 0; i < splits.length - 1; i++) {
                        select += '<option>' + splits[i] + '</option>';
                    }
                    document.getElementById('demo').innerHTML = '<select>' + select + '</select>';
                };
                http.open("POST", "newphp.php");
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                http.send();
            }
            receive();
        </script>

    </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.