私はdjangoとjQueryを使用しており、送信後にページをリロードせずにボタンビューを変更しようとしています。最初に押すとすべて問題ありませんが、2回目に押すと2つのPOSTリクエストが発生し、3回目から3回など、ボタンは変化しません。データベース内のデータは、ボタンを押すたびに変更されますが。
私のjqueryコードの何が問題なのか、ポストリクエストの乗算を防ぐ方法を教えてください
function send()
{
$('.valid').submit(function()
{
var a_id = $(this).attr('a_id');
var vl = $(this).attr('vl');
$.ajax(
{
data: {'a_id' : a_id},
type: 'POST',
url: 'vl/',
success: function(data, status)
{
$('#mark_'+a_id).html('<i class="icon-white icon-ok"></i> Correct!')
$('#mark_'+a_id).attr("id",'cor_'+a_id);
$('#cor_'+a_id).html('Not correct')
$('#cor_'+a_id).attr("id",'mark_'+a_id);
},
error: function(xhr, data)
{
alert('fail: ' + data +' answer #'+ a_id);
}
});
});
}
a_id は回答ID用で、テンプレートのボタンから取得されます
{% if answer.validity %}
<button id="cor_{{ answer.id }}" class="btn btn-inverse js-mark " a_id="{{answer.id}}" onclick = "send()" ><i class="icon-white icon-ok"></i> Correct answer</button>
{% else %}
<button id="mark_{{ answer.id }}" class="btn btn-inverse js-mark" a_id="{{answer.id}}" onclick = "send()" >Mark this answer as correct</button>
{% endif %}
views.py 部分:
def question_vl(request, question_id):
context_instance=RequestContext(request)
question = get_object_or_404(Question, pk=question_id)
if request.user == question.author:
if request.method == 'POST':
if(request.POST.get('a_id')):
a = Answer.objects.get(pk=request.POST.get('a_id'))
if a.validity==False:
a.validity = True
else:
a.validity = False
a.save()
return HttpResponse("")