我试图通过AJAX将所选选项拉入django视图。它只打印出第一个选择的选项,而不是第二个或第三个选项,依此类推。如果我在ajax中传递一个字典,它会在视图中接收它。所以错误不在视图中,因为getlist正在收集字典。但是,当我使用template.html中的变量时,它只能获得超过1的值。我试过添加" []"名称和身份后,但没有成功。我也尝试过来自其他答案的一些javascript,但没有结果。
template.html
<div id="manytomany-container">
{% if custommany1.name != 'None' %}
<label>{{ custommany1.name }}:</label>
<p><select name="custommany1" multiple="multiple" id="company-custommany1">
{% if company.custom_many1 %}
{% for selected in company.custom_many1.all %}
<option selected="selected" name="custommany1" value="{{ selected }}">{{ selected }}</option>
{% endfor %}
{% for option in custommany1_options.all %}
{% if option not in company.custom_many1.all %}
<option name="custommany1" value="{{ option }}">{{ option }}</option>
{% endif %}
{% endfor %}
{% else %}
{% for option in custommany1_options %}
<option name="custommany1" value="{{ option }}">{{ option }}</option>
{% endfor %}
{% endif %}
</select></p>
{% else %}
<input type="hidden" id="company-custommany1">
{% endif %}
</div>
$(document).ready(function(){
$('#company-form-submit').click(function() {
var company_id = document.getElementById("companyID").value;
var company_name = document.getElementById("id_company-company_name").value;
var company_custommany1 = document.getElementById("company-custommany1").value;
$.ajax({
method: "POST",
url: "{% url 'companies:company_update' %}",
data: {
'company_id': company_id,
'company_name': company_name,
'company_custommany1': company_custommany1,
},
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
},
success: function(response) {
$('.company-form-container').html(response);
}
});
});
});