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

基于AJAX与Laravel实现访问数实时增减功能

Solution for Real-Time Visitor Count Update

Let's get that visitor count updating in real-time without a page refresh! Right now your AJAX is handling the button state perfectly, but it's not touching the count display. Here's how to fix this end-to-end:

Step 1: Update Your Backend to Return the New Count

First, make sure your Laravel controller (the one handling the urlVisit endpoint) returns the updated visitor count as JSON after processing the visit/unvisit request. This gives your frontend the fresh number it needs:

// In your controller method
public function toggleVisit(Request $request)
{
    // Your existing logic to add/remove the visitor record goes here...
    
    // Get the updated count
    $place = Place::findOrFail($request->place_id);
    $visitorCount = $place->visitors->count();
    
    // Return it as JSON
    return response()->json(['count' => $visitorCount]);
}

Step 2: Refactor Your HTML for Easier Updates

Let's split the count and text into separate elements so we can update them independently without rewriting the entire <h5>:

<h5 class="visitor-count">
    <span class="count">{{ $place->visitors->count() }}</span>
    <span class="count-text">
        {{ $place->visitors->count() === 1 ? 'person has visited this place' : 'people have visited this place' }}
    </span>
</h5>

Step 3: Modify the AJAX Success Handler to Update the Count

Now update your JavaScript to use the returned count value and update both the number and the text (to handle singular/plural correctly):

$('.visit').on('click', function (event) {
    event.preventDefault();
    var buttonToChange = $(this);
    // Use the button's data-id instead of event.target to avoid issues with nested elements
    var placeId = buttonToChange.data("id");

    $.ajax({
        method: 'POST',
        url: urlVisit,
        data: {
            place_id: placeId,
            _token: token
        },
        success: function(response){
            var newCount = response.count;
            var countElement = $('.count');
            var countTextElement = $('.count-text');

            // Update the button state (your existing logic works great!)
            if(buttonToChange.hasClass('btn-visited')){
                buttonToChange.addClass('btn-not-visited').removeClass('btn-visited');
                buttonToChange.html('Not Visited');
            } else {
                buttonToChange.addClass('btn-visited').removeClass('btn-not-visited');
                buttonToChange.html('Visited');
            }

            // Update the count number
            countElement.text(newCount);

            // Update the text to handle singular/plural
            if(newCount === 1){
                countTextElement.text('person has visited this place');
            } else {
                countTextElement.text('people have visited this place');
            }
        },
        // Optional: Add an error handler to catch issues
        error: function(xhr){
            console.error('Error updating visit status:', xhr.responseText);
            // Maybe revert the button state if the request fails?
        }
    });
});

Key Improvements:

  • Reliable Place ID: Uses buttonToChange.data("id") instead of event.target to avoid problems if your button has nested icons/text.
  • Dynamic Text Updates: Handles the singular/plural text switch based on the new count.
  • Error Handling: Added a basic error handler to help debug if something goes wrong.
  • Clear Separation: Splitting the HTML elements makes updating specific parts easier and cleaner.

Once you implement these changes, clicking the "Visited"/"Not Visited" button will immediately update both the button state and the visitor count without needing to refresh the page.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:18:41