这是我的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));
}
咨询documentation。
打印二维阵列 - javascript我正在尝试打印子元素。在this example之后。怎么做?。$myarray = array("DO"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'), "JOCKEY"=>a…
如果我得到url(''),我该如何使用另一个URL - javascript我是新手,正在写这篇文章,但是如果源上没有图像,那么我只有空白。有人可以告诉我,如果我正在获取背景图像,如何获取/images/no-image.jpg:url();这是我的代码:<div class="uk-clearfix uk-position-relative"> <div class="recipeb…
粗糙的Unicode->没有CLDR的语言代码? - javascript我在写字典应用。如果用户键入Unicode字符,我想检查该字符是哪种语言。例如字 - returns ['zh', 'ja', 'ko'] العربية - returns ['ar'] a - returns ['en', 'fr', …
在JavaScript函数中转义引号 - javascript我正在尝试将变量传递给javascript函数。根据用户的选择,它可以是文本或图像。这里已经讨论了类似的问题,但我无法解决。在php中,我这样编码:if ($choice == 1) { $img = '<img src = "../folder/'.$_SESSION["img"].'…
如何在没有for循环的情况下在Javascript中使用Django模板标签 - javascript我想在JavaScript中使用模板变量:我的问题是在javascript代码中使用for循环,for循环之间的所有事情都会重复..但我不想要....下面粘贴了我的代码..有人可以告诉我更好的方法吗这..因为这看起来很丑..这是我的代码: {% block extra_javascript %} <script src="/static/js…