javascript - 在ajax生成的选择标签中添加选项

标签 javascript php jquery ajax

这是我的ajax代码

 <script type="text/javascript">
    $('#right_make').change(function() {
      var make = document.getElementById('right_make').value;
      alert(make);
      $.ajax({
        url: 'get.php',
        async: true,
        cache: false,
         data: {make:make},
         dataType: "html",
        type:'post',
        success: function (result) {
          var select = document.getElementById('right_model');

        select.insertAdjacentHTML('beforeend', result);
           }
      });
    });
    </script>

我正在获取从后端 php 恢复的 html 形式的数据,我想将此数据附加到选择标记中,如下所示

<select name="model" id="right_model" class="custom-select c_model right_model">
    <option value="">Model</option>
</select>

我尝试了上述方法,但它在选项之间产生了间隙, 这是我从后端附加的内容

<?php

include 'includes/config.php';
include 'includes/database.php';
$make=$_POST['make'];

$stmt=$db->prepare("SELECT distinct  `model` FROM `car` WHERE make=?");
$stmt->bind_param("s",$make);
$stmt->execute();
$stmt->bind_result($model);
while ($stmt->fetch()) {
    echo "<option>".$model."<option>";
}
?>

知道该怎么做吗?

最佳答案

通常,如果您想与 php 服务器通信一些数据,您可以使用 JSON。

JSON 保留了一个非常示例的解决方案,可以将 javascript 或 php 转换为非常示例的字符串。之后,您可以将 JSON 转换为 php、Javascript 或其他内容...

你可能会这样做,因为 php 不理解 javascript,当然 javascript 也不理解 php。

当你使用ajax传递数据时,你可以这样做:

$.ajax({
        url: 'get.php',
        async: true,
        cache: false,
         data: {make:JSON.stringify (make)},      // Traduce to simply string.
         dataType: "html",
        type:'post',
        success: function (result) {
          var select = document.getElementById('right_model');

        select.insertAdjacentHTML('beforeend', result);
           }
      });

然后,当你在 php 中获取数据时,你可以这样做:

$make=json_decode ($_POST['make']);    // Traduce to php.

当您使用 echo 时:

echo json_encode ("<option>".$model."<option>");

最后在你的 JavaScript 中:

success: function (result) {
      var select = document.getElementById('right_model');

    select.insertAdjacentHTML('beforeend', JSON.parse (result));
       }

咨询documentation .

关于javascript - 在ajax生成的选择标签中添加选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892650/

相关文章:

javascript - jQuery 切换属性值

javascript - React Native/Redux - setState - 在现有状态转换期间无法更新

php - 如何通过ajax在php中插入多个同名输入

javascript - JS变量等于html数据属性

javascript - 带边框的 Div 在 dragend 上调整大小

javascript - 添加cookie过期日期

php - 获取下拉选择以将用户定向到新页面(MySQL && P4A 应用程序框架)

php - Blade 模板,@yield 中的@yield()

php - 如何在 Laravel 7 中将注册服务单例传递给另一个注册服务的构造函数?

jquery - Kendo Grid 更改事件触发问题(当我单击一行时触发两次)