首页 > 解决方案 > 下拉 Onchange 并将 JavaScript 值传递给 PHP

问题描述

您好,我有一个关于如何将 JavaScript 值发送到 PHP 的问题。

这是我的表格:

在此处输入图像描述

来自数据库的下拉问题:

在此处输入图像描述

小提琴代码

<form action="action/survey">
          <div class="form-group">
            <label class="control-label col-sm-2" for="email">Select Question</label>
            <div class="col-sm-10">
              <select class="form-control" id="mySelect" onchange="option()">
                <?php
                $sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = $id"); 

                while ($q = mysqli_fetch_array($sql)) {
                 ?>
                  <option value="<?php echo $q[0]?>"><?php echo $q[2]?></option>
                 <?php
                }
                ?>
              </select>
            </div>

          </div>
          <div class="form-group">
            <label class="control-label " for=""></label>
          </div>
          <?php 
          $sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = 1 AND survey_qID = 1");
          $d1= mysqli_fetch_array($sql);
          ?>
          <div class="form-group">
            <label class="control-label col-sm-2" for="">Question</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="" placeholder="" value="<?php echo $d1[2]?>">
            </div>
          </div>
          <?php 
          $variable = $d1[3];
          $z = 1;
          $piece = explode(",", $variable);
          foreach ($piece as $key => $value) {

            ?>

            <div class="form-group">
            <label class="control-label col-sm-2" for="">Option <?php echo $z?> </label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="" placeholder="" value="<?php echo $value?>">
              </div>
            </div>
            <?php
            $z++;
          }
          ?>
          <div class="text-center">
          <button type="submit" class="btn btn-default" name="">Update</button>
          </div>
        </form>

JavaScript:

function option(){
    var x = document.getElementById("mySelect").value; 
    document.getElementById("demo").innerHTML = "You selected: " + x;
}

我想要的是,如果我在下拉列表中选择 1 个值,则选项的值必须发送到此查询中的 PHP 变量:

SELECT *, (
    SELECT GROUP_CONCAT(answer) AS `option`
    FROM `survey_anweroptions` 
    WHERE survey_qID = sq.survey_qID
) `option` 
FROM `survey_questionnaire`sq
WHERE sq.survey_ID = 1 
    AND survey_qID = (**the value of option will go here**)

标签: javascriptphp

解决方案


您应该使用名称而不是 id。并执行 print_r($_POST) 检查天气发布数据是否到来。在您使用 ajax 调用您的 php 脚本之前,您也不需要 javascript


推荐阅读