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

Laravel中用JQuery和AJAX切换按钮更新Div内容遇异常

Laravel AJAX 更新Div内容问题解决

问题场景

开发Laravel项目时,尝试实现无刷新更新Div内容:页面加载时显示当日所有比分,切换按钮到live状态时加载实时比分,切回all状态时恢复当日比分。但实际出现两个问题:

  1. 切换后生成重复的Div结构
  2. 切回all状态时功能失效

控制器代码

public function index(){
    $data = $this->client->fixtures()->getFixtures(['date' => date('Y-m-d')]);
    return view('index')->with('details', $data);
}

public function getScores(Request $request){
    $id = $request->id;
    if($id == 'live'){
        $liveScores  =  $this->client->fixtures()->getFixtures(['live' => 'all']);
    }

    if($id == 'all') {
        $liveScores  =  $this->client->fixtures()->getFixtures(['date' => date('Y-m-d')]);
    }

    return response()->json([
        'liveScores' => $liveScores
    ]);
}

初始视图渲染代码

@foreach($details['response'] as $detail)  
    <div class="kf_opponents_wrap2">
        <div class="kf_opponents_wrap">
            <p>{{$detail['league']['name']}}</p>
            <div class="kf_opponents_dec">
                ....
            </div>
        </div>
    </div>
@endforeach

AJAX逻辑代码

function sendAjaxRequest(element,urlToSend) {
    var clickedButton = element;
    
    $.ajax({type: "GET",
        url: urlToSend,
        dataType:"json",
        data: { id: clickedButton.val() },
        success:function(response){
            $(" .kf_opponents_wrap2").html('');
            var result = response.liveScores.response;
           
            if (result.length > 0) {
                Object.keys(result).map(k => {
                    $(" .kf_opponents_wrap2").append('
                    <div class="kf_opponents_wrap">\
                     <p>'+result[k].league.name+'</p>\                                    
                     <div class="kf_opponents_dec">\
                     .......
                     ....
                     </div>\
                    </div>' 
                    );
                });
            }
        }
    });
}

$(document).ready(function(){
    $(" #text_onoff").on( 'click' ,function() {
        $('#onoff').prop('checked' , $('#onoff').prop('checked') ? false : true).change();
    });

    $('#onoff').on('change', function(){
        $(this).val(this.checked ? 'live' : 'all');
        sendAjaxRequest($(this),'{{ route('getScores') }}');
    });  
});

问题分析与解决方案

1. 重复Div问题

原因:初始视图中@foreach循环每次都会生成一个.kf_opponents_wrap2容器,导致页面存在多个同类型元素。AJAX执行时会清空所有该类元素并追加内容,最终出现重复结构。

修复:将.kf_opponents_wrap2容器移到循环外部,作为唯一的父容器:

<div class="kf_opponents_wrap2">
    @foreach($details['response'] as $detail)  
        <div class="kf_opponents_wrap">
            <p>{{$detail['league']['name']}}</p>
            <div class="kf_opponents_dec">
                ....
            </div>
        </div>
    @endforeach
</div>

2. 切回all状态失效问题

原因:控制器未处理$id为空或异常的情况,且AJAX未做容错处理,空数据时无任何提示,看起来像功能失效。

修复:

  • 优化控制器逻辑,添加默认分支并确保返回结构稳定:
public function getScores(Request $request){
    $id = $request->id ?? 'all'; // 默认设为all
    if($id == 'live'){
        $liveScores  =  $this->client->fixtures()->getFixtures(['live' => 'all']);
    } else { // 覆盖all及其他异常情况
        $liveScores  =  $this->client->fixtures()->getFixtures(['date' => date('Y-m-d')]);
    }

    // 确保response结构始终存在,避免前端报错
    return response()->json([
        'liveScores' => $liveScores ?? ['response' => []]
    ]);
}
  • 优化AJAX回调,处理空数据场景并简化遍历逻辑:
success:function(response){
    const container = $(".kf_opponents_wrap2");
    container.html('');
    const result = response.liveScores?.response || [];

    if (result.length > 0) {
        // 直接遍历数组,无需Object.keys
        result.forEach(item => {
            container.append(`
                <div class="kf_opponents_wrap">
                    <p>${item.league.name}</p>                                    
                    <div class="kf_opponents_dec">
                        .......
                        ....
                    </div>
                </div>
            `);
        });
    } else {
        // 空数据时显示提示
        container.append('<p class="no-data">暂无比分数据</p>');
    }
}

额外优化建议

  • 给.kf_opponents_wrap2添加唯一ID(如scores-container),用ID选择器替代类选择器,避免误操作其他元素:$("#scores-container").html('');
  • 给AJAX添加错误回调,方便排查请求失败情况:
error: function(xhr, status, error) {
    console.error('请求失败:', error);
    $("#scores-container").html('<p class="error">加载数据失败,请稍后重试</p>');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 01:21:00