如何使用JQuery和Django(ajax + HttpResponse)?

TIM*_*MEX 4 python django jquery

假设我有一个AJAX函数:

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

当我的"View"在Django中执行时,我想返回HttpResponse('1')'0'.

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

Tom*_*eys 16

典型的工作流程是让服务器将JSON对象作为文本返回,然后在javascript中解释该对象.在您的情况下,您可以从服务器返回文本{"httpresponse":1},或使用python json libary为您生成.

JQuery有一个很好的json-reader(我只是阅读了文档,所以我的例子中可能有错误)

使用Javascript:

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

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")
Run Code Online (Sandbox Code Playgroud)

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           
Run Code Online (Sandbox Code Playgroud)

  • 几个星期前,有人给了我一个很好的答案:http://stackoverflow.com/questions/1457735/django-models-are-not-ajax-serializable (3认同)