这是我的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>";
}
?>
有什么想法吗?
答案 0 :(得分:0)
通常,如果要与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));
}