【发布时间】:2021-01-05 11:07:28
【问题描述】:
我在我的测试应用程序中发送用户答案数组,我得到两个数组(其中一个正确填写,但另一个为空)。同样在控制台中,我注意到我正在处理请求(POST 和 GET)。我应该如何通过 ajax POST 发送数组以便只发送一次?
Sripts.js:
function sendAnswers() {
$.ajax({
type: "POST",
url: 'result',
data: {
res_list: resultList()
},
success: function () {
}
})
location.href = 'result'
}
function resultList() {
let allAnswersList = [];
allAnswersList = getCheckedCheckBoxes().concat(getSequence())
return allAnswersList
}
Views.py:
def result(request):
user_answers_list = request.POST.getlist('res_list[]')
context = {'res_lst': user_answers_list }
return render(request, 'main/result.html', context)
urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='home'),
path('registration/', include('django.contrib.auth.urls')),
path('registration', views.registration, name='registration'),
path('test', views.test, name='test'),
path('result', views.result, name='result')
]
结果.html:
<div class="alert alert-warning mt-2" id="mainArea">
{% for question in testing %}
<div class="alert alert-secondary mt-2" id="questionArea{{ forloop.counter0 }}">
<form method="post" id='testForm' data-url="{% url 'test' %}">
{% csrf_token %}
<table>
<thead>
<tr>
<th>{{ forloop.counter }}. {{ question.1 }}</th>
</tr>
</thead>
</table>
{% if question.4 %}
{% for images in img %}
{% if images.picture == question.4 %}
<img src="{{ images.picture.url }}" class="mainImg" alt=""><br>
{% endif %}
{% endfor %}
{% endif %}
{% if question.0 == '1' %}
{% for el in question.2 %}
<label>
<input type="checkbox" class="checkbox" onclick="getCheckedCheckBoxes()"
name="{{ question.1 }}"
value="{{ el }}" id="{{ question.1 }}"/> {{ el }}
</label><br>
{% endfor %}
{% else %}
<label>
{% for num in question.2 %}
<h6>{{ forloop.counter }}. </h6>
<select id="myselect" class="myselect" name="myselect" onchange="getSequence()">
<option disabled selected></option>
{% for el in question.2 %}
<option value="{{ el }}" id="{{ question.1 }}{{ forloop.counter0 }}"
label="{{ el }}">
</option>
{% endfor %}
</select><br>
{% endfor %}
</label>
{% endif %}
</form>
</div>
{% endfor %}
<button type="button" value="snd" id="sendAnsButton" onclick="sendAnswers()" class="button">Завершить тест</button>
</div>
控制台:
[18/Sep/2020 16:36:33] "POST /result HTTP/1.1" 200 33229
[18/Sep/2020 16:36:33] "GET /result HTTP/1.1" 200 33229
【问题讨论】:
标签: python-3.x django ajax request