这是我能想到的最基本的例子。它涵盖了添加/删除功能:
HTML:
<select name="test_add" id="test_add">
{% for position in all_positions %}
<option value="{{ position.id }}">{{ position }}</option>
{% endfor %}
</select>
{% for position in user_positions %}
<span id="positions">
{{ position }}
<input type="hidden" class="position_id" value="{{ position.id }}">
<a class="delete-position" href="#;">X</a>
</span>
{% endfor %}
网址:
url(r'^ajax_test_delete/$',
'ajax_test_delete',
name='ajax_test_delete'),
url(r'^ajax_test_add/$',
'ajax_test_add',
name='ajax_test_add'),
url(r'^ajax_test_page/$',
'ajax_test_page',
name='ajax_test_page'),
意见:
def ajax_test_page(request):
profile = request.user.get_profile()
all_positions = Position.objects.all_with_gender().filter(id__lt=50).order_by('position')
user_positions = profile.positions.order_by('positiontimestamp__timestamp')
return render(request, 'videos/ajax_test_page.html', {'user_positions': user_positions, 'all_positions': all_positions})
def ajax_test_delete(request):
position_id = int(request.POST['position_id'])
position = Position.objects.get(id=position_id)
profile = request.user.get_profile
PositionTimestamp.objects.get(profile=profile, position=position).delete()
return HttpResponse()
def ajax_test_add(request):
position_id = int(request.POST['position_id'])
position = Position.objects.get(id=position_id)
profile = request.user.get_profile()
add_new = PositionTimestamp(profile=profile, position=position)
add_new.save()
return HttpResponse()
JS:
// TEST AJAX //
$("a.delete-position").live('click', function(){
// use named variables in the outer function -- $(this) refers to the response in the inner function
var span = $(this).parent();
var position_id = $(this).siblings('input.position_id').val();
$.post('/ajax_test_delete/', {'position_id': position_id}, function(response) {
span.remove();
});
});
$("#test_add").change(function(){
var position_id = $(this).find('option:selected').val();
$.post('/ajax_test_add/', {'position_id': position_id}, function(response) {
var position_name = $("#test_add option:selected").text();
var span = $('<span>' + position_name + '</span>');
span.append($('<input type="hidden" class="position_id" value="' + position_id + '">' ));
span.append($('<a class="delete-position" href="#;">X</a>'));
$('#positions').append($(span));
});
});