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

jQuery中Select默认值无法触发getJSON页面加载数据求助

Fix: Load Default 30-Day Data on Page Load

Hey Darren, let's get your default analytics data loading properly. The issues you're hitting come from two main snags: invalid API URL formatting and timing/execution order problems. Here's how to fix it step by step:

1. Fix the API URL (Critical!)

Your current URL uses &—that's HTML-encoded syntax, but in JavaScript we need raw & for query string separators. This was breaking your API request (returning empty data), which is why all stats showed 0 when you called datePeriod() directly.

Update the $.getJSON URL to use & instead of &:

$.getJSON(`https://discovrbookings.innocraft.cloud/?module=API&method=API.get&format=json&idSite=2&period=day&date=last${datePeriod}&token_auth=68aa5bd12137f13255dcb98794b65dff`, (data) => {
  // ... rest of your data processing code
});

2. Ensure Code Runs After the DOM is Ready

Your original code might be trying to interact with the #DateSelector element before it exists on the page. Wrap your initialization logic in $(document).ready() to guarantee elements are available when you need them.

3. Properly Trigger Initial Data Load

Now that the URL is fixed, you can safely trigger the initial load either by calling datePeriod() directly or using .trigger('change'). We'll also clean up the event binding for better maintainability.

Full Working Code

Here's the revised, fully functional version of your code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="DateSelector" id="DateSelector">
  <option value="7">Last 7 Days</option>
  <option value="14">Last 14 Days</option>
  <option selected value="30">Last 30 Days</option>
  <option value="90">Last 90 Days</option>
  <option value="365">Last 365 Days</option>
</select>

<span id="visitors"></span>
<span id="uniq_visitors"></span>
<span id="pageviews"></span>
<span id="uniq_pageviews"></span>
<span id="actions"></span>
<span id="outlinks"></span>
<span id="bounces"></span>
<span id="avgtime"></span>

<script>
function datePeriod() {
  let datePeriod = $("#DateSelector").val();
  $("#DateShow").html(datePeriod);
  
  // Fixed API URL with proper query string separators
  $.getJSON(`https://discovrbookings.innocraft.cloud/?module=API&method=API.get&format=json&idSite=2&period=day&date=last${datePeriod}&token_auth=68aa5bd12137f13255dcb98794b65dff`, (data) => {
    let visitors = 0;
    let uniq_visitors = 0;
    let pageviews = 0;
    let uniq_pageviews = 0;
    let actions = 0;
    let outlinks = 0;
    let bounces = 0;
    let avgtime = 0;
    
    // Safer iteration: handle both array and single object responses
    if (Array.isArray(data)) {
      data.forEach(item => {
        visitors += item.nb_visits || 0;
        uniq_visitors += item.nb_uniq_visitors || 0;
        pageviews += item.nb_pageviews || 0;
        uniq_pageviews += item.nb_uniq_pageviews || 0;
        actions += item.nb_actions || 0;
        outlinks += item.nb_outlinks || 0;
        bounces += item.bounce_count || 0;
        avgtime += item.avg_time_on_site || 0;
      });
    } else {
      // Fallback for if the API returns a single object instead of an array
      visitors = data.nb_visits || 0;
      uniq_visitors = data.nb_uniq_visitors || 0;
      pageviews = data.nb_pageviews || 0;
      uniq_pageviews = data.nb_uniq_pageviews || 0;
      actions = data.nb_actions || 0;
      outlinks = data.nb_outlinks || 0;
      bounces = data.bounce_count || 0;
      avgtime = data.avg_time_on_site || 0;
    }
    
    // Update UI with calculated values
    $("#visitors").html(visitors);
    $("#uniq_visitors").html(uniq_visitors);
    $("#pageviews").html(pageviews);
    $("#uniq_pageviews").html(uniq_pageviews);
    $("#actions").html(actions);
    $("#outlinks").html(outlinks);
    $("#bounces").html(bounces);
    $("#avgtime").html(avgtime / datePeriod);
  });
}

// Bind change event to the dropdown (cleaner than inline onchange)
$("#DateSelector").on("change", datePeriod);

// Initialize data load when page is ready
$(document).ready(() => {
  // No need to set val('30') since the option already has selected="selected"
  // If you ever need to override the default later, uncomment this:
  // $("#DateSelector").val('30');
  
  // Trigger initial data fetch
  datePeriod();
});
</script>

Key Improvements:

  • Fixed API URL: Ensures the API can correctly parse your request parameters.
  • DOM Ready Wrapper: Prevents errors from trying to interact with elements before they exist.
  • Safer Data Handling: Checks if the API response is an array or single object, so your code won't break if the response format changes slightly.
  • Cleaner Event Binding: Uses jQuery's .on() instead of inline onchange for more maintainable code.

Now when the page loads, it will automatically fetch and display the 30-day analytics data, and the dropdown will work smoothly when you select other date ranges.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:43:02