【问题标题】:How to use JQuery and Django (ajax + HttpResponse)?如何使用 JQuery 和 Django (ajax + HttpResponse)?
【发布时间】:2010-12-04 09:36:17
【问题描述】:

假设我有一个 AJAX 函数:

function callpage{
$.ajax({
    method:"get",
    url:"/abc/",
    data:"x="+3
    beforeSend:function() {},
    success:function(html){
       IF HTTPRESPONSE = "1" , ALERT SUCCESS!
    }
    });
    return false;
}
}

当我的“视图”在 Django 中执行时,我想返回 HttpResponse('1')'0'

我如何知道它是否成功,然后发出警报?

【问题讨论】:

    标签: jquery python django


    【解决方案1】:

    典型的工作流程是让服务器返回一个 JSON 对象作为文本,然后返回interpret that object in the javascript。在您的情况下,您可以从服务器返回文本 {"httpresponse":1} ,或者使用 python json 库为您生成它。

    JQuery 有一个不错的 json-reader(我刚刚阅读了文档,所以我的示例中可能存在错误)

    Javascript:

    $.getJSON("/abc/?x="+3,
        function(data){
          if (data["HTTPRESPONSE"] == 1)
          {
              alert("success")
          }
        });
    

    姜戈

    #you might need to easy_install this
    import json 
    
    def your_view(request):
        # You can dump a lot of structured data into a json object, such as 
        # lists and touples
        json_data = json.dumps({"HTTPRESPONSE":1})
        # json data is just a JSON string now. 
        return HttpResponse(json_data, mimetype="application/json")
    

    Issy 提出的另一种观点(很可爱,因为它遵循 DRY 原则)

    def updates_after_t(request, id): 
        response = HttpResponse() 
        response['Content-Type'] = "text/javascript" 
        response.write(serializers.serialize("json", 
                       TSearch.objects.filter(pk__gt=id))) 
        return response           
    

    【讨论】:

    • 几周前有人给了我一个很好的答案:stackoverflow.com/questions/1457735/…
    • 另一种从模型返回 json 数据的方法... def updates_after_t(request, id): response = HttpResponse() response['Content-Type'] = "text/javascript" response.write(serializers.serialize("json", TSearch.objects.filter(pk__gt=id))) 返回响应
    【解决方案2】:

    考虑使用 jQuery 的 taconite plugin,而不是做所有这些杂乱的、低级的 ajax 和 JSON 的东西。您只需调用后端,剩下的就交给它了。它有详细的文档且易于调试——尤其是当您将 Firebug 与 FF 结合使用时。

    【讨论】:

    • 我不喜欢这些“创建 xml 并发生奇迹”类型的东西。将某人指向backbone.js或类似的东西要好得多。
    • @peregrine: 你用过 jquery-taconite 吗?这不是魔术,它只是以干净、可预测的方式处理了许多恼人的细节。代码本身非常易读,就像我使用过的 malsup 中的大多数内容一样。我认为 taconite 并不比使用 C 编译器或 Python 解释器更神奇——它们都让我的生活更轻松。我在汇编程序中编程多年,并了解裸铁(或硅)发生了什么,但这并不让我喜欢它。我在很多事情上都使用 jQuery,所以对于我正在从事的大多数项目来说,这是一个给定的。
    猜你喜欢
    • 2013-10-09
    • 2016-09-03
    • 2011-04-08
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2011-11-12
    相关资源
    最近更新 更多