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

使用jQuery AJAX调用JSON数据遇问题,求技术排查(附代码)

Troubleshooting Your jQuery AJAX & JSON Issue

Hey there! Let's break down the potential issues in your code and fix them one by one to get your search functionality working properly:

1. Duplicate jQuery Import

You've included jQuery twice in your code (once before Bootstrap, once later in the script section). This can cause unexpected conflicts and is unnecessary. Keep only one import, and ensure it loads before Bootstrap (since Bootstrap depends on jQuery to function):

<!-- Keep this single jQuery import before Bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

Remove the second jQuery import that appears after your HTML content.

2. Mismatched JSON Data Fields (Likely the Root Cause)

This is probably why your code isn't behaving as expected. In your filter logic, you're checking for value.name and value.location, but when appending results to the list, you're using value.userId, value.id, value.title, and value.body.

If your data.json follows a structure like this (common placeholder JSON):

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  }
]

Then name and location don't exist on these objects, so value.name.search(expression) will throw an error. Update your filter to use the actual fields present in your JSON:

// Use fields that match your data.json structure
if (value.title.search(expression) != -1 || value.body.search(expression) != -1 || value.userId.toString().search(expression) != -1) {
  // Your existing append logic here
}

3. Missing Error Handling

Your $.getJSON call doesn't handle failures (like if data.json is missing, has invalid syntax, or there's a cross-origin issue). Add a .fail() callback to debug what's going wrong:

$.getJSON('data.json', function(data){
  // Your existing each/filter logic here
})
.fail(function(jqXHR, textStatus, errorThrown) {
  console.error("Error loading JSON:", textStatus, errorThrown);
  $('#result').html('<li class="list-group-item text-danger">Failed to load data. Check your browser console for details.</li>');
});

4. Frequent AJAX Requests on Keyup

Every key press triggers a new AJAX request, which can lead to performance issues and out-of-order responses (older requests finishing after newer ones). Add a debounce function to delay the request until the user stops typing (e.g., 300ms):

// Debounce helper to prevent excessive requests
function debounce(func, delay) {
  let timeoutId;
  return function() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, arguments), delay);
  };
}

// Wrap your keyup logic in debounce
$('#search').keyup(debounce(function () {
  $('#result').html('');
  var searchField = $('#search').val().trim();
  
  // Skip request if search field is empty
  if (!searchField) return;

  var expression = new RegExp(searchField, 'i');
  $.getJSON('data.json', function(data){
    $.each(data, function(key, value){
      // Updated filter with correct fields
      if (value.title.search(expression) != -1 || value.body.search(expression) != -1 || value.userId.toString().search(expression) != -1) {
        $('#result').append('<li class="list-group-item"><span class="muted">'+value.userId+'</span> | <span class="text-muted">'+value.id+'</span> | <span class="text-muted">'+value.title+'</span> | <span class="text-muted">'+value.body+'</span></li>')
      }
    });
  })
  .fail(function(jqXHR, textStatus, errorThrown) {
    console.error("Error loading JSON:", textStatus, errorThrown);
    $('#result').html('<li class="list-group-item text-danger">Failed to load data. Check console for details.</li>');
  });
}, 300)); // Wait 300ms after last key press to trigger request

5. Verify data.json Location & Format

Double-check these details:

  • data.json is in the same folder as your HTML file (or adjust the path in $.getJSON if it's in a subfolder like ./data/data.json)
  • The JSON file is valid. You can validate it by copying its content into a JSON checker tool to ensure no syntax errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:38:59