I trying to implement a search button using ajax and django where I send the selected value the server, but I can't get the selected value from the select HTML tag , the variable value is always empty ({"obj":""}) ??
HTML :
div class="col-2">
<label style="color : white;">Title</label>
<select name="da" id="da" class="form-control da">
<option selected></option>
{% for obj in ds %}
<option value="{{obj}}">{{obj}}</option>
{%endfor%}
</select>
<button type="submit" class="btn btn-warning btn-lg search">ajax</button>
</div>
ajax :
var value = $('#da').val();
console.log(value)
$(document).ready(function() {
$('.search').click(function(){
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
$.ajax({
type: "GET",
url: '/search/ajax/',
data: JSON.stringify({'obj' : value}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-CSRFToken": csrftoken
},
success: function(response) {
do somthing ......
},
error: function(rs, e) {
alert(rs.responseText);
}
});
})
});
view.py
def filter_ajax(request):
if request.method == 'GET':
value = request.GET.get('obj')
print(value)
You must set the value
variable on click. Also, I'm not much acquainted with Django, but do you need JSON.Stringify
?
var value; $(document).ready(function() { $('.search').click(function() { value = $('#da').val(); // Set here var csrftoken = $('[name="csrfmiddlewaretoken"]').val(); $.ajax({ type: "GET", url: '/search/ajax/', data: JSON.stringify({ 'obj': value }), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, success: function(response) { do somthing...... }, error: function(rs, e) { alert(rs.responseText); } }); }) });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.