我需要一个基于父级的下拉列表,使用Laravel 5中的ajax

时间:2015-12-03 07:29:05

标签: ajax laravel-5

控制器功能代码

public function siteadmin_get_subcategory(Request $request)
{

    $product_id = $request->input('product');   

    $sub_category=array(
        'product_id'=>$product_id,
    );
    $return = Category_model::get_subcategory($sub_category);       
    //return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
    return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);

}

模型功能代码(获取产品ID的子类别)

public static get_subcategory($sub_category)
{
    return DB::table('le_product')->where('product_id', '=', $sub_category)->get();

}

查看JavaScript代码

这是我基于父

的下拉列表的Ajax概念
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  

<script>
    $(document).ready(function(){
    $('#product_id').change(function(){
        var product = $('#product_id').val();
        if(product != 0) {
            $.ajax({
                type:'post',
                url:"<?php echo base_url('SiteadminController/siteadmin_getsub_category')?>",
                data: { id:product },
                cache:false,
                success: function(returndata){
                    $('#subcategory').html(returndata);
                }
            });
        }
    })
})
</script>

2 个答案:

答案 0 :(得分:0)

您需要在AJAX中调用正确的URL:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  

<script>
    $(document).ready(function(){
    $('#product_id').change(function(){
        var product = $('#product_id').val();
        if(product != 0) {
            $.ajax({
                type:'post',
                url:"<?php echo action('SiteadminController@siteadmin_getsub_category')?>",
                data: { id:product },
                cache:false,
                success: function(returndata){
                    $('#subcategory').html(returndata);
                }
            });
        }
    })
})
</script>

AJAX也期待JSON,从我看到,你将返回HTML。所以你需要做一个Controller动作来返回JSON。

答案 1 :(得分:0)

get_subcategory1

public function get_subcategory1()
    {
      /*$product_id = $request->input('product_id');
      $data=array(
                'product_id'=>$product_id,
                );*/
    //$get_subcategory1 = Category_model::get_subcategory1();
    return view('siteadmin.get-subcategory1');
    }