#javascript #jquery #django
#язык JavaScript #jquery #джанго
Вопрос:
Я пытаюсь создать приложение для викторины с использованием Django и js с использованием функции amp;.ajax jquery, все работает нормально, за исключением выбранных ответов, я вижу результат и задаю все вопросы, почему это происходит, я создал ввод для ответов, которые я могу просмотреть на странице. моя проблема заключается в публикации этого выбранного ответа
views.py
@csrf_exempt def save_quiz_view(request, pk): if request.is_ajax(): questions = [] data = request.POST data_ = dict(data.lists()) # delet the csrf_token data_.pop('csrfmiddlewaretoken') for k in data_.keys(): print('key', k) question = Question.objects.get(text=k) questions.append(question) print(questions) user = request.user quiz = Quiz.objects.get(pk=pk) score = 0 # Get the ratio of user's answers multiplier = 100 / quiz.number_of_questions results = [] correct_answer = None for answer in questions: a_selected = request.POST.get(answer.text) print("selected:", a_selected) if a_selected != "": question_answers = Answer.objects.filter(question=answer) # loop through an answers of praticlar question for a in question_answers: if a_selected == a.text: # question is correct if a.correct: score = 1 correct_answer = a.text else: # both cases display the correct answer if a.correct: correct_answer = a.text results.append({ str(answer): { 'correct_answer': correct_answer, 'answered': a_selected } }) else: results.append({str(answer): 'not answered'}) score_ = score * multiplier Result.objects.create(quiz=quiz, user=user, score=score_) if score_ gt;= quiz.required_score: return JsonResponse({ 'passed': True, 'score': score_, 'results': results, 'correct_answer': correct_answer }) else: return JsonResponse({ 'passed': "False", 'score': score_, 'results': results, 'correct_answer': correct_answer })
файл js
const quizBox = document.getElementById('quiz-box') // let data let url = window.location.href $.ajax({ type: 'GET', url: `${url}data`, success: function(response){ const data = response.data data.forEach(e =gt; { // question as a key and the answers as values for (const [question, answers] of Object.entries(e)) { // console.log(answers); quizBox.innerHTML =` lt;hrgt; lt;div class="mb-2"gt; lt;stronggt;${question}lt;/stronggt; lt;/divgt; ` answers.forEach(answer =gt; { quizBox.innerHTML = ` lt;div class="mb-1 answers"gt; lt;input type="radio" class="ans" id="${question}-${answer}" name="${question}" vlaue="${answer}"gt; lt;lable for="${question}"gt;${answer}lt;/labelgt; lt;/divgt; ` }) } }) }, error: function(error){ console.log(error); } }) const quizForm = document.querySelector("#quiz-form") const csrftoken = document.getElementsByName('csrfmiddlewaretoken'); const sendData = () =gt; { const elements = [...document.getElementsByClassName('ans')] const data = {} data['csrfmiddlewaretoken'] = csrftoken[0].value elements.forEach(e =gt; { if (e.checked) { // set in html name amp; value data[e.name] = e.vlaue } else { // if there isn't any key wit element name if (!data[e.name]) { data[e.name] = null } } }) $.ajax({ type: 'POST', url: `${url}save/`, // sign to the object above data: data, success: function(response) { console.log(response); }, error: function(error){ console.log(error); } }) } quizForm.addEventListener('submit', e =gt; { e.preventDefault() sendData() })