我正在做一个项目管理工具Web应用程序。我希望用户可以从下拉菜单中选择“用户”,然后单击“添加成员”,那么该成员将显示在该成员下方的某个位置。这就是我在做什么。
请不要担心样式。我尚未完成UI。
view.py
def member_select(request):
if request.method == 'GET':
selection = request.GET.get('id',None)
if selection:
selected_member = User.objects.filter(pk=selection)
return selected_member
project_index.html
<form action="" method="GET" id="selection-form">
{% csrf_token %}
<select id="member_list">
{% for user in user %}
<option>
{{ user.username }}
</option>
{% endfor %}
</select>
<input type="button" value="Add member" id="selection-button">
</form>
base.html
<script>
var url = $( '#selection-form' ).attr( 'action' );
$("selection-button").onclick(function (e) {
e.preventDefault();
$.ajax({
type:'GET',
url:url,
data:{
id:$('#member_list').val()
},
success:function (result) {
alert('okay');
},
error:function (result) {
alert('error');
}
});
});
</script>
答案 0 :(得分:0)
也许使用空的<p class='member-name'><p>
并
在jQuery成功函数中选择后
更改为
success:function (result) {
$('.member-name').text(result);
},
答案 1 :(得分:0)
尝试一下(未完全测试)
from django.core import serializers
from django.http import HttpResponse
def member_select(request):
selection = request.GET.get('id',None)
if selection:
data = serializers.serialize('json',User.objects.filter(pk=selection))
else:
data = {}
return HttpResponse(data, content_type='application/json')
来自文档https://docs.djangoproject.com/en/2.0/topics/serialization/
在javascript ajax函数中,响应应该是用户对象(如果存在)或json字符串为空
<form action="" method="GET" id="selection-form">
{% csrf_token %}
<select id="member_list">
{% for user in user %}
<option value="{{user.pk}}">{{ user.username }}</option>
{% endfor %}
</select>
<input type="button" value="Add member" id="selection-button">
</form>
<di id='res'></div>
$("#selection-button").on('click', function(e) {
e.preventDefault();
var value =$('#member_list').val();
$.ajax({
type:'GET',
url:'.',
data:{
id:value
},
success:function (result) {
alert('okay');
$('#res').append(result);
console.info(result);
},
error:function (result) {
alert('error');
}
});
});