Django |使用ajax(jquery)显示选择选项的名称值而不是id
这是ajax代码
$('.addtasksubmit').click(function(e) {
e.preventDefault();
$.ajax({
url: 'addtodo',
type: "POST",
data: {
title: $('#task-title').val(),
category: $('#catsel option:selected').val(),
'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()
},
success: function(response) {
console.log(response)
$('.todos-box').append(`
<a href="#" class="category-link">${response.category}</a>
`)
$("#addtodo").trigger('reset');
$("#exampleModal").modal('hide');
}
})
})
所以 ${response.category} 给了我类别的ID,但我需要查看类别名称
,这是views.py
response = {
'title': request.POST['title'],
'category' : request.POST['category'],
}
todo = Todo.objects.create(title=response['title'],
category=Category.objects.get(id=response['category']),
user=request.user)
todo.save()
return JsonResponse(response, safe=False)
这是HTML
<select name="category" class="form-select form-select-sm" id="catsel">
<option seleted>Choose Category</option>
{% for category in categories %}
<option value="{{ category.id }}">{{ category }}</option>
{% endfor %}
</select>
有没有办法用ajax查看类别名称而不是id?或者我如何获取类别的名称及其 ID。
抱歉我的英语不好..
this is the ajax code
$('.addtasksubmit').click(function(e) {
e.preventDefault();
$.ajax({
url: 'addtodo',
type: "POST",
data: {
title: $('#task-title').val(),
category: $('#catsel option:selected').val(),
'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()
},
success: function(response) {
console.log(response)
$('.todos-box').append(`
<a href="#" class="category-link">${response.category}</a>
`)
$("#addtodo").trigger('reset');
$("#exampleModal").modal('hide');
}
})
})
So ${response.category} gives me the id of the category but i need the category name to be viewed
and this is views.py
response = {
'title': request.POST['title'],
'category' : request.POST['category'],
}
todo = Todo.objects.create(title=response['title'],
category=Category.objects.get(id=response['category']),
user=request.user)
todo.save()
return JsonResponse(response, safe=False)
this is HTML
<select name="category" class="form-select form-select-sm" id="catsel">
<option seleted>Choose Category</option>
{% for category in categories %}
<option value="{{ category.id }}">{{ category }}</option>
{% endfor %}
</select>
is there any way to view the category name with ajax not the id? or how can i get the name of the category with its id.
sorry for my bad english..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过 5 天的尝试,我解决了这个问题。
将其添加到视图
和 ajax
中,并添加了
dataType: 'json'
so i have solved this problem after 5 days of trying.
added this to the views
and ajax
and also added
dataType: 'json'
从模板中获取包含类别的 HTML 选择输入会很有帮助。根据您发布的内容,请将views.py调整为
It would be helpful to get the HTML select input with the categories from the template. Based on what you posted please adjust the views.py to