这是我的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/