Javascript 在从ajax生成的select标记中添加选项
这是我的ajax代码Javascript 在从ajax生成的select标记中添加选项,javascript,php,jquery,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: fal
<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);
}
});
$make=json_decode ($_POST['make']); // Traduce to php.
然后,当您在php中获取数据时,您可以这样做:
$.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);
}
});
$make=json_decode ($_POST['make']); // Traduce to php.
使用echo时:
echo json_encode ("<option>".$model."<option>");
请参阅。您所说的在选项之间产生间隙是什么意思?例如和空选项,在每个非空选项之后,请确保文件中没有空回音或打印。而且之前和之后都没有空间是的,有一个缺口!!