在laravel中通过javascript获取数组

问题描述 投票:0回答:1

我尝试在我的类别下使用get list of optionsproducts,到目前为止我能做到这一点

但问题是,如果我选择多个类别,则只返回第一类的选项。

DEMO

codes

functions

// load my page
public function create()
{
  $categories = Category::all();
  $statuses = Status::all();
  return view('admin.landings.create', compact('categories', 'statuses'));
}


//get option of categories and return it as json
public function getlandingsubspecifications($id)
{
  $specifications = DB::table('products')
  ->where('category_id', $id)
  ->join('product_subspecification', 'product_subspecification.product_id', '=', 'products.id')
  ->join('subspecifications', 'subspecifications.id', '=', 'product_subspecification.subspecification_id')
  ->groupBy('subspecifications.id')
  ->get();

  return response()->json($specifications);
}

JavaScript

<!-- get subspecifications -->
<script type="text/javascript">
  $(document).ready(function() {
    $('select[name="category_id"]').on('change', function() {
      var subcategoryID = $(this).val();
      if(subcategoryID) {
      $.ajax({
        url: '{{ url('admin/getlandingsubspecifications') }}/'+encodeURI(subcategoryID),
        type: "GET",
        dataType: "json",
        success:function(data) {
            $('select[name="spacefication_id"]').empty();
            $.each(data, function(key, value) {
                  $('select[name="spacefication_id"]').append(
                        "<option class='form-control' value='"+ value['id'] +"'>"+ value['title'] +"</option>");
            });
        }
      });
      }else{
        $('select[name="spacefication_id"]').empty().append("<option value='' selected>Select</option>");
      }
    });
  });
</script>

HTML

<div class="col-md-12">
  <div class="col-md-6">
    {{Form::label('category_id', 'Categories')}}
    <select class="form-control tagsselector" name="category_id" multiple="multiple">
     <option value="">Select Categories</option>
     @foreach($categories as $category)
       <option value="{{$category->id}}">{{$category->title}}</option>
     @endforeach
    </select>
   </div>
   <div class="col-md-6">
    {{Form::label('spacefication_id', 'Spacefications')}}
    <select class="form-control tagsselector" name="spacefication_id" multiple="multiple">
      <option value="">Select Spacefications</option>
    </select>
  </div>
</div>

UPDATE

my network result on selecting categories

screen1

javascript php json ajax laravel
1个回答
0
投票

将数组的id传递给whereIn函数

public function getlandingsubspecifications($arrayOfIds)
{
    $specifications = DB::table('products')
           ->whereIn('category_id',[$arrayOfIds])
        //rest of code
}
© www.soinside.com 2019 - 2024. All rights reserved.