如何使用Django,Ajax,jQuery提交表单而不刷新页面?

我是django的新手。我需要简单的例子。如何使用Django,Ajax,jQuery提交表单(发布)而不刷新页面?

这是我的表单,视图和模板:

views.py

from django.shortcuts import *

from django.template import RequestContext

from linki.forms import *

def advert(request):

if request.method == "POST":

form = AdvertForm(request.POST)

if(form.is_valid()):

print(request.POST['title'])

message = request.POST['title']

else:

message = 'something wrong!'

return render_to_response('contact/advert.html',

{'message':message},

context_instance=RequestContext(request))

else:

return render_to_response('contact/advert.html',

{'form':AdvertForm()},

context_instance=RequestContext(request))

forms.py(使用“ ModelForm”的表单)

from django import forms

from django.forms import ModelForm

from linki.models import Advert

class AdvertForm(ModelForm):

class Meta:

model = Advert

模板(表单html代码)

<html>

<head>

</head>

<body>

<h1>Leave a Suggestion Here</h1>

{% if message %}

{{ message }}

{% endif %}

<div>

<form action="" method="post">{% csrf_token %}

{{ form.as_p }}

<input type="submit" value="Submit Feedback" />

</form>

</div>

</body>

</html>

回答:

如果你打算将ajax提交与jquery一起使用,则不应从视图中返回html。我建议你改为这样做:

HTML:

<html>

<head>

</head>

<body>

<h1>Leave a Suggestion Here</h1>

<div class="message"></div>

<div>

<form action="" method="post">{% csrf_token %}

{{ form.as_p }}

<input type="submit" value="Submit Feedback" />

</form>

</div>

</body>

</html>

js

$('#form').submit(function(e){

$.post('/url/', $(this).serialize(), function(data){ ...

$('.message').html(data.message);

// of course you can do something more fancy with your respone

});

e.preventDefault();

});

views.py

import json

from django.shortcuts import *

from django.template import RequestContext

from linki.forms import *

def advert(request):

if request.method == "POST":

form = AdvertForm(request.POST)

message = 'something wrong!'

if(form.is_valid()):

print(request.POST['title'])

message = request.POST['title']

return HttpResponse(json.dumps({'message': message}))

return render_to_response('contact/advert.html',

{'form':AdvertForm()}, RequestContext(request))

这样你就可以将响应放入messagediv中。而不是返回纯HTML,你应该返回json。

以上是 如何使用Django,Ajax,jQuery提交表单而不刷新页面? 的全部内容, 来源链接: utcz.com/qa/432435.html

回到顶部