Error Message
Uncaught SyntaxError: "[object Object]" is not valid JSON
at JSON.parse (<anonymous>)
at Object.success ((index):19:40)
at j (jquery-1.11.2.min.js:2:27295)
at Object.fireWith [as resolveWith] (jquery-1.11.2.min.js:2:28108)
at x (jquery-1.11.2.min.js:4:22061)
at XMLHttpRequest.b (jquery-1.11.2.min.js:4:25980)
문제 상황
setInterval(() => {
fetchCheatingHistory();
}, 1000);
var fetchCheatingHistory = function () {
$.ajax({
url: "http://localhost:8080/cheating_history",
type: "GET",
dataType: "json",
success: function (data) {
// update the cheating history of div
var cheatingHistory = JSON.parse(data);
console.log(cheatingHistory);
$.each(cheatingHistory, function (index, value) {
var cheatingHistoryDiv = $("#cheatingHistory");
cheatingHistoryDiv.append("<p>" + value + "</p>");
});
},
error: function () {
console.log("error");
},
});
};
JavaScript에서 JQuery, Ajax를 이용해 http get요청으로 JSON 데이터를 받아오려 했는데, 콘솔창에서 저런 오류가 남.
해결
dataType: "json"
을 작성해주면, JQuery에서 자동으로 JSON response를 파싱하여 넘겨준다고 한다.
참 편하네.
Line 12
이 필요없이, console.log(data);
면 된다는 것.
setInterval(() => {
fetchCheatingHistory();
}, 1000);
var fetchCheatingHistory = function () {
$.ajax({
url: "http://localhost:8080/cheating_history",
type: "GET",
dataType: "json",
success: function (data) {
// update the cheating history of div
// 삭제: var cheatingHistory = JSON.parse(data);
console.log(data);
$.each(data, function (index, value) {
var cheatingHistoryDiv = $("#cheatingHistory");
cheatingHistoryDiv.append("<p>" + value + "</p>");
});
},
error: function () {
console.log("error");
},
});
};