Flask Ajax返回数据在jQuery中解析时出现Uncaught SyntaxError异常的问题求助
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 ofjson.dumps(): Flask'sjsonify()function automatically sets the correctContent-Typeheader and handles JSON formatting/encoding properly. If you're usingreturn json.dumps(data), Flask will send it astext/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
forEachis wrong:element => [should beelement => {(use curly braces for the function body, not brackets). - The string concatenation for the image URL is broken:
asset('storage/'.element.image)should beasset('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
- Clear your browser cache and retest the request.
- In DevTools, confirm the
getCategoryCourse/request returns a 200 status code, and the Response tab shows valid JSON (no extra characters or HTML). - Verify the
Content-Typeheader in the response isapplication/json.
内容的提问来源于stack exchange,提问作者user17236681

