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

Flask Ajax返回数据在jQuery中解析时出现Uncaught SyntaxError异常的问题求助

Troubleshooting JSON Parse Error with jQuery AJAX and Flask Backend

First off, that Uncaught SyntaxError you're hitting is almost always tied to a few common gotchas when pairing jQuery AJAX with Flask. Let's break down the most likely culprits and actionable fixes tailored to your code:

Key Troubleshooting Steps

1. Stop manually parsing JSON (this is probably your main issue!)

jQuery automatically parses JSON responses if your Flask backend sends the correct Content-Type: application/json header. When you call jQuery.parseJSON(response) on an already-parsed JavaScript object, jQuery will first convert that object to a string like "[object Object]"—which is definitely not valid JSON, hence the "unexpected character" error at column 2.

Looking at your code, remove the jQuery.parseJSON() call entirely. Replace:

var respons = jQuery.parseJSON(response);

With:

var respons = response; // Or just use `response` directly in your code

2. Verify your Flask backend is returning valid JSON correctly

Even if you think your backend returns valid JSON, double-check these details:

  • Use jsonify() instead of json.dumps(): Flask's jsonify() function automatically sets the correct Content-Type header and handles JSON formatting/encoding properly. If you're using return json.dumps(data), Flask will send it as text/plain, which can lead to parsing issues or hidden whitespace/encoding problems.
    Example Flask code:
    from flask import jsonify
    
    @app.route('/getCategoryCourse/<int:id>')
    def get_category_course(id):
        # Fetch your course data here
        course_data = [...]
        return jsonify(course_data)
    
  • Check for extra output in the response: In your browser's DevTools (Network tab), look at the full response content for your getCategoryCourse/ request. Sometimes Flask might return debug HTML (like a 404 error page) or extra whitespace/newlines from print statements, comments, or template leftovers—none of which are valid JSON.

3. Fix syntax errors in your jQuery code

While not directly causing the JSON error, these will break your code once the parsing issue is fixed:

  • The arrow function syntax in your forEach is wrong: element => [ should be element => { (use curly braces for the function body, not brackets).
  • The string concatenation for the image URL is broken: asset('storage/'.element.image) should be asset('storage/' + element.image).

Revised Snippet of Your Fixed Code

Here's the corrected success callback section to implement these changes:

success: function(response) {
  console.log(response); // Check this first to confirm it's already a parsed object
  $('.courseFilters').empty();
  if (response.length == 0) {
    $('.courseFilters').append('هیچ رکوردی ثبت نشده است');
  } else {
    response.forEach(element => {
      $('.courseFilters').append(`<div class="row">
        <div class="col-lg-4 mb-3">
          <div class="card">
            <img src="${asset('storage/' + element.image)}" class="card-img-top" alt="${element.title}">
            <div class="card-body">
              <h5 class="card-title">${element.title}</h5>
            </div>
            <div class="card-footer p-0">
              <div class="d-flex justify-content-between">
                <div class="d-flex align-items-center ps-3">${element.body}</div>
                <div>
                  <a href="${element.path()}">
                    <span class="bg-info d-inline-block p-2"><i class="fas fa-cart-plus fa-2x"></i></span>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>`);
    });
  }
}

Final Checks

  1. Clear your browser cache and retest the request.
  2. In DevTools, confirm the getCategoryCourse/ request returns a 200 status code, and the Response tab shows valid JSON (no extra characters or HTML).
  3. Verify the Content-Type header in the response is application/json.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 11:22:32