TypeError: Cannot read properties of undefined (reading 'forEach') with ajax method
У меня есть ajax-функция:
<div class="quiz-box"></div>
...
const url = window.location.href
const quizBox = document.getElementById('quiz-box')
let data
$.ajax({
type: 'GET',
url: `${url}data/`,
success: function(response){
// console.log(response)
data = response.data
data.forEach(el => {
for (const [question, answers] of Object.entries(el)){
quizBox.innerHTML = `
<b>${question}</b>
`
}
});
},
error: function(error){
console.log(error)
},
})
Который получает данные из представления django.
Теперь это приводит к ошибке в консоли:
Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') at Object.success at j
at Object.fireWith [as resolveWith]
at x
at XMLHttpRequest.b
Почему возникает эта ошибка и как я могу ее предотвратить?
используйте опциональный оператор chaining (?.), чтобы проверить, не является ли переменная нулевой, прежде чем обращаться к ней.
изменение :
data.forEach(el => {.....
к :
data?.forEach(el => {.....