You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何通过jQuery实现日期选择器动态更新订单总数

问题修复方案

核心问题分析

  1. Controller返回错误:当前AJAX请求后,Controller返回的是完整视图页面,而非AJAX需要的纯订单数数据,导致JS无法获取最新的订单统计值。
  2. JS数据获取错误:代码中JSON.parse("{{ json_encode($tot_o) }}")调用的是页面首次渲染时的初始值,并非AJAX请求返回的最新数据。
  3. Shopify API查询逻辑问题:当前选中日期时仅设置created_at_max,会查询所有早于该日期的订单,而非选中当天的订单。

步骤1:修正Controller逻辑

修改index()方法,区分AJAX请求和普通请求,AJAX请求返回JSON数据,普通请求返回视图:

public function index(Request $request)
{
    if($request->has('selected_date')){
        $selected_date = $request->selected_date;
        // 修正Shopify API查询条件,确保查询选中当天的订单
        $url = "https://MYAPIKEY@MYSTORE.myshopify.com/admin/api/2022-10/orders/count.json?status=any&created_at_min={$selected_date}T00:00:00&created_at_max={$selected_date}T23:59:59";
    }else{
        $selected_date = date('Y-m-d');
        $url = "https://MYAPIKEY@MYSTORE.myshopify.com/admin/api/2022-10/orders/count.json?status=any&created_at_min={$selected_date}T00:00:00";
    }

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $json_response = curl_exec($curl);
    curl_close($curl);
    $result_1 = json_decode($json_response, TRUE);
    $tot_o = $result_1['count'] ?? 0;

    // 区分AJAX请求和普通请求
    if ($request->ajax()) {
        return response()->json(['tot_o' => $tot_o]);
    }

    return view('dashboard.index', ['sum' => $sum, 'tot_o' => $tot_o]);
}

步骤2:修正JavaScript代码

移除错误的初始值引用,直接从AJAX返回的JSON数据中提取最新订单数并更新页面元素:

<script>
$(document).on('change', '#date', function (e) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        type: 'GET',
        url: '/home',
        data: {selected_date: $('#date').val()},
        success:function(response){
            // 清空并更新span内容
            $('#tot_o').text(response.tot_o);
            console.log(response.tot_o);
        },
        timeout:10000,
        error:function(xhr){
            console.error('请求失败:', xhr.responseText);
        }
    });
});    
</script>

额外注意事项

  • 确保路由/home指向修改后的index()方法。
  • 检查Shopify API的权限和版本有效性,避免因API版本过期导致请求失败。
  • 若需处理日期格式兼容问题,可在JS中对选中日期做格式化处理后再传递。

内容的提问来源于stack exchange,提问作者nikamata hukamuko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:15:28