Django:我简单的ajax实验出了什么问题?

时间:2010-03-09 19:19:39

标签: jquery ajax django

我试图了解Django + Jquery和Ajax如何协同工作。

只是一个简单的/ test / url显示单个输入表单,一旦提交,就会通过ajax从服务器检索答案。

为此,我写了一个非常小的观点:

def test(request):
    if request.is_ajax():
        from django.http import HttpResponse
        post_text = request.POST.get("post_data")
        return HttpResponse("{'response_text': '"+post_text+" recieved.'}", mimetype="application/json")
    else:
        return render_to_response('test.html', {},context_instance =RequestContext(request))

我已将此网址规则写入url.py中的urlpattern:

(r'^test/$', 'myapp.views.test'),

这是我的test.html模板:

<html>
  <head><title>template</title></head>

  <script type="text/javascript" src="/media/js/jquery.js"></script>

  <script type="text/javascript">
    $(document).ready(function() {
        $('#post_form').submit(function(event){
            event.preventDefault(); // cancel the default action
            var form = this;
            var data = {}
            data.post_data = $(form).find('input[@name=our_text]').val();

            $.post("/test/", 
                data, 
                function(responseData) {
                  alert(responseData.response_text);
                },
                "json"
            );
        });
    });
  </script>

  <body>
    <form id="post_form" method="post">
      INPUT: <input type="text" name="our_text" />
      <input type="submit" value="Add" />
    </form>
  </body>
</html>

在填写输入字段并提交后,我的www.mysite.com/test/上似乎没有任何回复。可能是什么问题?

2 个答案:

答案 0 :(得分:5)

jQuery 1.4不会解析无效的JSON。正如Alex Gaynor所提到的,你的JSON是无效的,因为它使用的是单引号,而不是双引号。

手工编写JSON很傻。使用库将python数据类型转换为JSON。再一次,正如Alex所说,Django已经为你发送了simplejson。或者,如果您使用的是Python2.6或更高版本,则json是标准库的一部分http://docs.python.org/library/json.html

from django.http import HttpResponse
from django.utils import simplejson

def test(request):
    if request.is_ajax(): 
        post_text = request.POST.get("post_data")
        response_dict = {'response_text': '"+post_text+" recieved.'}
        return HttpResponse(simplejson.dumps(response_dict), mimetype="application/json")
    else:
        return render_to_response('test.html', {},context_instance =RequestContext(request))

答案 1 :(得分:4)

对象(字典)的JSON键必须使用双引号引用,而不是单引号。你真的应该使用真正的JSON库,例如simplejson(django在django.utils.simplejson中包含)来生成你的JSON