在laravel处理两个独立的ajaxes的最佳方法是什么?

时间:2017-12-13 07:06:04

标签: javascript ajax laravel

所以我有一个页面有两个单独的ajax调用(使用laravel),当第一个执行时,第二个必须运行,但第二个ajax的选项在selectbox中。这是我的解决方案(心脏不好):

 public function getCategoryAjax(Request $request)
{
    $product = Product::where('category_id',$request->get('category_id'))->get();

    return $product;
}
public function getPriceAjax(Request $request)
{
    $withPrice = Product::where('category_id',$request->get('category_id'));
    if ($request->get('price') == 1){
        $withPrice=$withPrice->where('min_price','<', 1000000)->get();
    }elseif ($request->get('price') == 2){
        $withPrice=$withPrice->where('min_price','>', 1000000)->andWhere('max_price','<',2000000)->get();
    }


    return $withPrice;
}

第一个方法是第一个ajax,在第二个方法我正在做if ifif用于处理selectbox中的选项

所以这是我的问题,有更好的方法吗? enter image description here (左边的选择框是第二个ajax

1 个答案:

答案 0 :(得分:0)

我认为您正在询问更好的方法来处理 getPriceAjax(Request $ request)函数中的多个条件...

如果这是您的问题,则可以这样编写代码...

// Set all your min-max price rules in array, by this you can easily modilfy every price option rule..
protected $priceRules = array(
    1 => ["0", "1000000"],
    2 => ["1000000", "2000000"],
    3 => ["2000000", "3000000"],
    4 => ["3000000", "4000000"],
    // ... so on
);

public function getPriceAjax(Request $request) {
    $price = $request->get('price');
    // check given option is in array or not... some validation..
    if (isset($this->priceRules[$price])) {
        // It will dynamically handle all your price option query...
        $withPrice = Product::where('category_id', $request->get('category_id'))->whereBetween('price', $this->priceRules[$price])->get();
        return $withPrice;
    }
    return 'error';

}

希望它可以帮助您...