我是 Ajax 和 Django 的新手。为了简化问题,假设我有一个隐藏表单和两个对象,并且我要求用户单击对象的某些位置。每次点击都会填写表格的一部分。我希望为每个对象填写一次表格。所以总共两次。当为第一个主题填写表单时,我想通过 Ajax 将表单发送到服务器,而不刷新页面,并允许为第二个对象重新填写表单。但是,由于某种原因,我无法通过 ajax 发送表单。
这是我的代码:index.html:
<html>
<body>
<script src="{{ STATIC_URL }}prototype.js"></script>
<script src="{{ STATIC_URL }}jquery.js"></script>
<script>
objectID= 1;
num_obj = {{num_obj}}
function ajax_post(){
$('#inputform').submit(function() {
$.ajax({
type: 'POST',
url: '/index/',
data: $(this).serialize(),
success: function(data){alert(data)}
}); // end new Ajax.Request
});
}
function onDocumentMouseDown( event ) {
....do stuff
if (objectID < num_obj){
ajax_post()
}
if (objectID == num_obj){
$("form").submit();}
objectID ++;
$("form").clearForm();
document.forms[0].ObjectID.value = objectID;
}
</script>
<form action="" method="post" id="inputform">
<div id="ajaxwrapper">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
</div>
</form>
</body>
</html>
我的观点.py:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import *
from firstapp.forms import PracForm3
num_obj=2
def index(request):
Obj.objects.all().delete()
if request.method == 'POST':
form = PracForm3(request.POST)
print "\n\n\n\n\n"
if request.is_ajax():
print "yaaaaay AJAX"
print request.POST
else:
print "noooooo"
print "\n\n\n\n\n"
if form.is_valid():
cd = form.cleaned_data
.....
if cd['ObjectID'] == num_obj:
return HttpResponseRedirect('/submit')
else:
form = PracForm3()
dic = {'form': form, 'num_obj': num_obj, ...}
return render_to_response('index.html', dic, context_instance=RequestContext(request))
我的 urls.py:
from django.conf.urls import patterns, include, url
from firstapp.views import index, submit
from django.conf import settings
urlpatterns = patterns('',
('^index$', index),
('^submit$', submit),
)
出于某种原因,我的 Ajax 无法工作任何人都知道我做错了什么吗?