api已解码数据,但无法以表格形式工作 [英] Api have decode data but not work in form
本文介绍了api已解码数据,但无法以表格形式工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的create.blade.php文件,其中包含ajax函数API和HTML标记代码.
This is my create.blade.php file which include ajax function API and HTML tag code..
@extends('layouts.app')
@section('content')
<link rel="stylesheet" href="http://www.codermen.com/css/bootstrap.min.css">
<script src="http://www.codermen.com/js/jquery.js"></script>
<form enctype="multipart/form-data" method="post" action="{{route('post.store')}}" >
@csrf
<div class="form-group col-md-8">
Category<select name="category" id="category" class="form-control">
<option>select</option>
@foreach($categories as $category)
<option value="{{$category->id}}">{{$category->category}}</option>
@endforeach
</select>
</div>
<div class="form-group col-md-8">
Category<select name="subcategory" id="subcategory" class="form-control">
<option>select</option>
@foreach($subcategories as $subcategory)
<option value="{{$subcategory->id}}">{{$subcategory->subcategory}}</option>
@endforeach
</select>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function(){
var categoryID = $(this).val();
if(categoryID){
$.ajax({
type:"GET",
url:"{{url('/api/getSubcategory/')}}/"+categoryID,
success:function(res){
if(res){
$("#subcategory").empty();
$("#subcategory").append('<option>Select</option>');
$.each(res,function(key,value){
$("#category").append("<option value='"+key+"'>"+value+"</option>");
});
}else{
$("#subcategory").empty();
}
}
});
}else{
$("#subcategory").empty();
}
});
</script>
@endsection
这是我的控制器代码,其中包括create函数和getSubcategory函数
This is my controller code which include create function and getSubcategory function
public function create(){
$categories = Category::all();
$subcategories = Subcategory::all();
return view('post.create', compact('categories', 'subcategories'));
}
public function getSubcategory(Request $request){
$id = $request->id;
$subcategories = Subcategory::where('category_id',$id)->select
('Subcategory','id')->get();
{{ dd(json_decode($subcategories, true)); }}
// return view('post.create')->with('subcategories', json_decode($subcategories, true));
}
这是我的web.php
This is my web.php
Route::get('/post/create', 'PostController@create')->name('post.create');
Route::get('api/getSubcategory/{id}', 'PostController@getSubcategory' );
现在我的问题是API拥有数据并给我
Now my problem is API have data and give me
但是当我打开此页面并选择类别时仍未显示相关子类别
but when i open this page and select category still not show related subcategory
推荐答案
更改
$subcategories = Subcategory::where('category_id',$id)->select
('Subcategory','id')->get();
收件人
$subcategories = Subcategory::where('category_id',$id)->select
('Subcategory','id')->pluck('subcategory', 'id');
然后
return json_encode($subcategories);
可能需要在ajax成功函数中对其进行解码-尝试两者.
Possibly need to decode it in your ajax success function - try both.
这篇关于api已解码数据,但无法以表格形式工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文