[英]Adding options in select tag generated from 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标签中,如下所示
<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));
}
请查阅文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.