从属下拉列表不适用于Ajax中的PATH网址。
正常的URL对于Ajax调用来说工作正常。 “ http://localhost/ajax”,但在将PATH添加到网址时,例如“ http://localhost/ajax/drop”不起作用。
我在哪里做错了?
查看:
<html>
<head>
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
<script src="{{ asset('js/app.js') }}"></script>
</head>
<body>
<div class="container">
<h2>Dependent Dropdown</h2>
<div class="form-group">
<label for="hardware">Select Hardware:</label>
<select name="hardware" class="form-control">
<option value="">Choose Any one</option>
@foreach ($hardwares as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach
</select>
</div>
<div class="form-group">
<label for="component">Selected Component:</label>
<select name="component" class="form-control" disabled>
<option>Component</option>
</select>
</div>
</div>
<script>
jQuery(document).ready(function ()
{
jQuery('select[name="hardware"]').on('change',function(){
var hardwareID = jQuery(this).val();
if(hardwareID)
{
jQuery.ajax({
url : 'autoselect/component/' +hardwareID,
type : "GET",
dataType : "json",
success:function(data)
{
console.log(data);
jQuery('select[name="component"]').empty();
jQuery.each(data, function(key,value){
$('select[name="component"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}
else
{
$('select[name="component"]').empty();
}
});
});
</script>
</body>
</html>
控制器:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class AjaxController extends Controller
{
public function hardware()
{
$hardwares = DB::table('hardwares')->pluck("name", "id");
return view('index', compact('hardwares'));
}
public function component($id)
{
$components = DB::table("components")->where("hardwares_id", $id)->pluck("name", "id");
return json_encode($component);
}
}
路线:
Route::get('ajax', 'AjaxController@hardware'); //This is working.
Route::get('ajax/drop', 'AjaxController@hardware'); //This is not working.
Route::get('autoselect/component/{id}', 'AjaxController@component');
使用其组件对硬件进行依赖下拉。
答案 0 :(得分:0)
根据以下内容对您的js代码进行一些更改:
<script>
jQuery(document).ready(function (){
jQuery('select[name="hardware"]').on('change',function(){
var baseurl = window.location.protocol + "//" + window.location.host;
var hardwareID = jQuery(this).val();
if(hardwareID != ''){
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
jQuery.ajax({
url : baseurl + '/autoselect/component/' +hardwareID,
type : "GET",
dataType : "json",
cache: false,
success:function(data) {
console.log(data);
jQuery('select[name="component"]').empty();
jQuery.each(data, function(key,value){
$('select[name="component"]').append('<option value="'+ value +'">'+ value +'</option>');
});
}
});
} else {
$('select[name="component"]').empty();
}
});
});
</script>