我正在尝试使用 Ajax 制作一个过滤器,我想在下拉列表中选择的类别发生变化时显示图像。现在,我正在视图中显示所有图像,并且我想要进行 Ajax 调用,返回过滤后的 $images 数组以在视图中显示。但我被困住了。我不知道如何从控制器正确返回数据,因此我可以在视图中访问它。
index.blade.php 中带有下拉菜单的表单
{{ Form::open( array(
'route' => 'index.filter',
'method' => 'post',
'id' => 'form-filter'
) ) }}
{{ Form::select('category', $categories, 'default', array('id' => 'categories')) }}
{{ Form::close() }}
routes
Route::post( 'filter', array(
'as' => 'index.filter',
'uses' => 'MyController@filter'
) );
.js
$( '#form-filter' ).change( function() {
$.post(
$( this ).prop( 'action' ),
{
"id": $( '#categories' ).val()
},
function( data ) {
alert(data);
},
'json'
);
return false;
} );
控制器
public function filter()
{
Log::info(Input::get('id'));
$id = Input::get( 'id' );
if($id)
$images = Image::where('category_id', '=', $id);
return Response::json($images);
}
public function index()
{
$images = Image::all();
$categories = ..\Models\Category::lists('name', 'id');
return View::make('index', array('images' => $images, 'categories'=>$categories));
}