我试图创建一个从属选择字段,但是当我选择第一个字段时,其他字段什么都没有发生。我认为ajax代码无法正常工作,因为我在ajax函数调用开始时使用了警报,但没有出现警报,但我仍然不确定是什么问题。我的代码有什么问题,谁能帮助我解决这个问题。
HTML代码
<form method="POST" action="{{url('search')}}">
@csrf
<div class="input-group col-sm-10 mt-5 offset-sm-1">
<select class="form-control" name="city">
<option value="none">---Choose City---</option>
<?php foreach ($result['city_data'] as $city) {
?>
<option value="<?php echo $city->id;?>"> <?php echo $city->name;?> </option>
<?php } ?>
</select>
<select class="form-control" name="area">
<option>Choose City</option>
</select>
<div class="input-group-append">
<input type="submit" class="btn searchbutton" value="Search" name="search_button">
</div>
</form>
Ajax代码
<script type="text/javascript">
$(document).ready(function() {
$('select[name="city"]').on('change', function(e) {
var cityID = $(this).val();
if(cityID) {
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }})
e.preventDefault();
$.ajax({
url: '/myform/ajax/'+cityID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="area"]').empty();
$.each(data, function(key, value) {
$('select[name="area"]').append('<option value="'+ key +'">'+value+'</option>');
});
}
});
}
else{
$('select[name="area"]').empty();
}
});
});
</script>
web.php
Route::get('myform/ajax/{id}','services4uController@myformAjax');
Controller.php
public function myformAjax($id)
{
echo "<script>alert('Code reached to this stage');</script>";
$area = DB::table("area")
->where("id_city",$id)
->lists("name","id");
return json_encode($area);
}