【问题标题】:Django: What's wrong with my simple ajax experiment?Django:我的简单 ajax 实验有什么问题?
【发布时间】:2010-03-09 19:19:39
【问题描述】:

我正在尝试了解 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))

我已经在 urls.py 中将这个 url 规则写入了我的 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/ 上做任何回复。可能是什么问题?

【问题讨论】:

  • 你的视图被调用了吗?您的 POST 数据是否符合您的预期?另外,我建议使用 json 模块来处理对 json 的编码。
  • Firebug 是否显示任何类型的错误?

标签: jquery ajax django


【解决方案1】:

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))

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 感谢您的回答,我已经检查了链接,但仍然对如何将 simplejson 应用于我的视图感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多