在laravel中通过javascript获取数组

时间:2018-03-02 07:47:16

标签: javascript php json ajax laravel

我尝试get list of options在我的类别下使用的products到目前为止我可以做到

  

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

DEMO

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>

更新

my network result on selecting categories

screen1

1 个答案:

答案 0 :(得分:0)

将id数组传递给whereIn fucntion

public function getlandingsubspecifications($arrayOfIds)
{
    $specifications = DB::table('products')
           ->whereIn('category_id',[$arrayOfIds])
        //rest of code
}