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

Ali*_*ahi 5 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;
}
Run Code Online (Sandbox Code Playgroud)

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

所以这是我的问题,有没有更好的方法来做到这一点? 在此输入图像描述 (左边的选择框是第二个ajax

Abh*_*pta 0

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

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

// 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';

}
Run Code Online (Sandbox Code Playgroud)

希望它能帮助你...