AJAX和DJANGO组成

时间:2012-12-03 04:29:43

标签: javascript jquery python ajax django

我是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>

我的view.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))  

my 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不起作用,谁知道我做错了什么?

5 个答案:

答案 0 :(得分:3)

这可能与AJAX帖子的CSRF相关,您必须记住在每次POST请求时都将CSRF令牌作为POST数据传递。您可能需要添加此代码here,这些代码是关于Django + CSRF + AJAX的Django文档。

我在你的Django视图中注意到你正在重定向到“submit”通常使用ajax我不会重定向到不同的url,我会使用HttpResponse并返回一些字符串值,例如JSON。我也不知道为什么你的视图中有打印语句,除非你在调试器中进入该视图。对于测试/调试,您应该有一个变量,您可以为其分配一些字符串,然后将其传递回您的ajax。然后在你的ajax中你可以从视图中读取消息,就像这样。

def index(request):
    ...
    if request.is_ajax():
        msg = 'it worked'
    else:
        msg = 'i am sad'
    return HttpResponse(msg)
    ...

此外,您的javascript应该在ajax调用中具有成功和错误功能,您只是 取得成功所以你没有发现错误,鉴于你的javascript看起来有点像这样:

...
success: function(data){alert(data)}, 

error: function(data){alert(data)}
...         

看起来您可能会遇到几个问题。如果你还没有完成我给你的CSRF的东西,那么链接也是一个问题,如果你不想以优先的方式解决这个问题,请使用csrf_exempt。尝试上面的代码位,看看是否能为您带来进步。

答案 1 :(得分:1)

csrf令牌包含在$('#input-form')发布请求中,因此我认为不是问题所在。我认为问题是你没有在你的视图中将上下文转换为json。这来自docs example

import json
from django.http import HttpResponse

class JSONResponseMixin(object):
    """
    A mixin that can be used to render a JSON response.
    """
    response_class = HttpResponse

    def render_to_response(self, context, **response_kwargs):
        """
        Returns a JSON response, transforming 'context' to make the payload.
        """
        response_kwargs['content_type'] = 'application/json'
        return self.response_class(
            self.convert_context_to_json(context),
            **response_kwargs
        )

    def convert_context_to_json(self, context):
        "Convert the context dictionary into a JSON object"
        # Note: This is *EXTREMELY* naive; in reality, you'll need
        # to do much more complex handling to ensure that arbitrary
        # objects -- such as Django model instances or querysets
        # -- can be serialized as JSON.
        return json.dumps(context)

答案 2 :(得分:0)

您在ajax调用中请求/index/,但您的模式与/index匹配。

答案 3 :(得分:0)

可能由csrf引起,在方法名称有用之前添加@csrf_exempt

@csrf_exempt
def method(args):
    pass

答案 4 :(得分:0)

我注释掉了CSRF所以不是我的ajax功能不是问题。这是正确的方法:

function ajax_post(){ 
    $.ajax({ 
        type: 'POST',
        url: '/index/',
        data: $(this).serialize(),
        success: function(data){alert(data)}

     }); // end new Ajax.Request
}

感谢您的所有输入