2009-10-06 45 views
4

假设我有一个AJAX功能:如何使用JQuery和Django(ajax + HttpResponse)?

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'

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

回答

16

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

jQuery有一个很好的JSON阅读器(我刚才读的文档,所以有可能是在我的例子中的错误)

的Javascript:

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

Django的

#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   
+3

有人给了我几个星期前有关这个好回答:http://stackoverflow.com/questions/1457735/django-models-are-not-ajax-serializable – theycallmemorty 2009-10-06 20:45:17

+1

另一种方式返回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))) 返回响应 – ismail 2009-10-06 23:05:26

2

而不是做所有这些混乱的,低级别的ajax和JSON的东西,考虑使用jQuery的taconite plugin。你只需要打电话给后端,剩下的就完成了。它具有良好的文档记录并且易于调试 - 尤其是如果您使用带有FF的Firebug。

+1

我没有在这些“创建xml和魔术发生”类型的东西上出售。将某人指向backbone.js或类似的东西更好。 – peregrine 2011-07-21 02:56:24

+0

@peregrine:你有*使用过吗?jquery-taconite?这不是魔术,它只是以一种干净,可预测的方式处理的许多恼人的细节。代码本身非常易读,就像我用过的malsup中的大部分代码一样。我将taconite视为比使用C编译器或Python解释器更具魔力 - 它们都让我的生活更轻松。我在汇编程序中进行了多年的编程,并理解正在发生的事情,直到裸铁(或硅),但这并不会让我喜欢它。我使用jQuery做了很多事情,这是大多数我正在开发的项目中的一个给定的东西。 – 2011-07-21 03:17:27