我是Ajax的新手。我试图抓住所有的概念。我正在尝试通过ajax提交表单。这是我的代码
views.py:
def ajax_test1(request):
if request.POST:
form = ModelForm(request.POST)
if form.is_valid():
form.save()
print request.POST.get('name')
x = request.POST.get('name')
if request.is_ajax():
response_dict = {}
response_dict.update({'server_response':x})
return HttpResponse(json.dumps(response_dict),content_type='application/json')
else:
return HttpResponse('not ok')
else:
form = ModelForm()
return render(request,'test1.html',{'form':form})
Jquery的:
$(document).ready(function(){
$('#button').click(function{
var input_id = $('#id_name').val();
$.ajax({
type:'POST',
url:'/test1/',
datatype:'json',
data:{name:input_id},
success: function(json){
$('result').append(json.server_response);
},
headers:{'X-CSRFToken':csrf_token},
error: function(xhr,errmsg,err){
alert('Something worng');
}
});
});
});
HTML:
<form action="" method="POST" accept-charset="utf-8">
{% csrf_token %}
{{ form }}
<p><input id="button" type="submit" value="Continue →"></p>
</form>
<div id="result">
</div>
<div id="result1">
</div>
以上代码返回200响应,但数据未保存,并返回ServerResponse:未定义