当用户选择select选项时,我在Django中有以下HTML模板来发送请求。控制台根据用户选择的内容显示正确的值。我的问题是当我按下提交按钮时,我的POST在提交的视图上被发布为无。如何在按钮点击时发布它,我将按钮别名为my_select。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action = "{% url 'submitted' %}" form method = "POST">
{% csrf_token %}
<h2>Applications:</h3></br>
{% for app in retreivecheckbox %}
<li><input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }}
</li>
{% endfor %}
</div>
</div>
<div class="row">
<div class="col">
<label for="accesslevel"><h3>Access Level</h3></label>
<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
<option value=""> Please select your access level </option>
<option value="7"> Facility </option>
<option value="5"> Division </option>
<option value = "3"> Corporate </option>
<option value = "6"> Market </option>
<option value = "4"> Group </option>
</select>
</div>
<div class="col">
<label for="phi"><h3>PHI</h3></label>
<select class="form-control my_select" id="phi" title = "phi" >
<option value = ""> Please select if you need access to PHI data </option>
<option value = "0"> No </option>
<option value = "1"> Yes </option>
</select>
</div>
</div>
<div class="row">
<div class="container">
<div class="row">
<div class="col">
</br> </br>
<button href="{% url 'submitted' %}" class="btn btn-primary my_select" type = "submit"> Submit </button>
<script>
$(document).ready(function () {
$('.my_select').on('click', function () {
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid ').val();
$.ajax({ url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
;
},
});
});
});
</script>
</div>
</form>
答案 0 :(得分:1)
将您的按钮和javascript更改为:
<button class="btn btn-primary my_select" type="submit">Submit</button>
<script>
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid').val();
$.ajax({
url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
// do something with result
},
});
});
});
</script>
这是我通常使用的Jquery 3.2.1
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: "POST",
data: $(this).serialize()
}).done(function(xhr) {
// do something
});
});
还要更新您的选择元素
<select class="form-control my_select" id="phi" name="phi">
而不是
<select class="form-control my_select" id="phi" title = "phi" >
请注意我已将“title”attr更改为“name”