设置dataType:'json'后AJAX GET请求无法显示数据求助
dataType: 'json' Breaks Your AJAX Request Hey Chris, let's break down what's happening here and fix it.
The Root Issue
When you skip setting dataType: 'json', jQuery treats the server's response as plain text—so your console.log just prints the raw string you shared:
{"id":"1","post_id":"748037498494861","post_title":"laptop","image1":"team217.jpg","price":"1234"}{"id":"2","post_id":"740811329642473","post_title":"remote control car","image1":"team522.jpg","price":"50"}{"id":"4","post_id":"316194613858174","post_title":"Ipad 3","image1":"team523.jpg","price":"400"}
But this string isn't valid JSON! JSON requires a single top-level structure—either an object ({...}) or an array ([{...}, {...}]). Your response is three separate JSON objects mashed together without any wrapping. When you set dataType: 'json', jQuery tries to parse this invalid string and throws a parsing error, which is why the request fails.
Fixes to Try
1. Fix the Backend (Best Practice)
The cleanest solution is to adjust your backend to return a valid JSON array instead of concatenated objects. The correct response should look like this:
[{"id":"1","post_id":"748037498494861","post_title":"laptop","image1":"team217.jpg","price":"1234"},{"id":"2","post_id":"740811329642473","post_title":"remote control car","image1":"team522.jpg","price":"50"},{"id":"4","post_id":"316194613858174","post_title":"Ipad 3","image1":"team523.jpg","price":"400"}]
Once you do this, your original AJAX call with dataType: 'json' will work perfectly—jQuery will automatically parse the response into a JavaScript array of objects.
2. Work Around It on the Frontend (If Backend Can't Be Changed)
If you can't modify the backend, you can manually clean up the response string and parse it yourself. Skip setting dataType (or set it to 'text'), then fix the format before parsing:
$.ajax({ url: "your-request-url-here", type: "GET", // Don't set dataType: 'json' here success: function(rawResponse) { try { // Wrap concatenated objects in an array by fixing the gaps between them const fixedJson = "[" + rawResponse.replace(/}{/g, "},{") + "]"; const parsedData = JSON.parse(fixedJson); console.log("Parsed data:", parsedData); // Now you can work with parsedData as an array of objects } catch (error) { console.error("Failed to parse JSON:", error); } }, error: function(xhr, status, err) { console.error("Request error:", status, err); } });
The replace(/}{/g, "},{") part replaces every }{ (the gap between your objects) with },{, turning the string into a valid array structure before parsing.
内容的提问来源于stack exchange,提问作者chris keenan

