JavaScript onClick 添加带有下拉列表的表单字段我需要填充 PHP MySQL 查询

我有一个 JavaScript 函数,当用户单击一个按钮时,它会在表单中添加另一行。我需要在此行中添加一个下拉菜单,以查询 mySQL DB 以加载公司的数据。


HTML:


<input type="button" class="center tmid" value="Add New Line" id="add_btn" name="add_btn" onclick="newLine(<?php echo $rowId; ?>, 'timecard')">

JavaScript:


function newLine(a,page) { 


  if (page == 'timecard') {

    //get total rows in the table and subtract the header row

    var rowCount = $('#tsTable tr').length;

    var i = rowCount - 1; 


    var rowId = parseFloat(a)+parseFloat(i);

    var tcId = this.tcId.value;


    $.get('functions/getCompany.php', function(result){

      var companyList = result;     

    });


    //create new row data       


     var newRowData = '<tr><input name="tcdid[]" type="text" value="'+rowId+'"><td><input type="date" name="jobDate[]" id="date'+rowId+'" value=""></td><td><input type="text" class="input-short" name="hours[]" id="h'+rowId+'" value=""></td><td><input type="text" class="input-short" name="ot[]" id="ot'+rowId+'" value=""></td><td><input type="text" class="input-short" name="km[]" id="km'+rowId+'" value=""></td><td class="nopadding"><select name="company[]" id="company'+rowId+'"></td><td><input type="text" name="ticket[]" id="ticket'+rowId+'" value=""></td><td><input type="text" name="wo[]" id="wo'+rowId+'" value=""></td><td><input type="text" name="details[]" id="d'+rowId+'" value=""></td><td class="td-shorter" ><input type="button" value="X" name="delete" class="btnDelete" onclick="deleteTimeLine(this,'+ rowId +',0)"></td></tr>';           


    //append new row to bottom of the table

    $(newRowData).appendTo($("#tsTable tbody"));

}

PHP:


function getCompany() {

    global $conn;

    $sqlC ="SELECT companyName 

            FROM customers 

            ORDER BY companyName ASC";

    $resultC = $conn -> query($sqlC);


    if($resultC === false){

        user_error("Query failed: ".$conn->error."<br />".$resultC);

        return false;

    }


所以我想在 getCompany() 函数中添加填充了结果的公司下拉列表。我该怎么办?任何帮助,将不胜感激。


谢谢!


动漫人物
浏览 79回答 1
1回答

拉莫斯之舞

您通常会在 javascript 端使用 AJAX 调用来执行此操作:$.get('/path/to/file.php', function (result) {&nbsp; &nbsp; console.log(result); // do something with result returned}然后在php方面:<?php // /path/to/file.php// perform your query, set variablesif ($success) {&nbsp; &nbsp; echo json_encode([&nbsp; &nbsp; &nbsp; &nbsp; 'status' => 'success',&nbsp; &nbsp; &nbsp; &nbsp; 'html' => '<option value='.$companies['companyName'].'>'.$companies['companyName'].'</option>'&nbsp; &nbsp; ]);}echo json_encode([&nbsp; &nbsp; 'status' => 'error',&nbsp; &nbsp; 'message' => 'Something went wrong, handle this']);
打开App,查看更多内容
随时随地看视频慕课网APP