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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1527641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:29:40  来源:igfitidea点击:

How to use JQuery and Django (ajax + HttpResponse)?

jquerypythondjango

提问by TIMEX

Suppose I have an AJAX function:

假设我有一个 AJAX 函数:

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

When my "View" executes in Django, I want to return HttpResponse('1')or '0'.

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

How can I know if it was successful, and then make that alert?

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

回答by Tom Leys

The typical workflow is to have the server return a JSON object as text, and then interpret that object in the javascript. In your case you could return the text {"httpresponse":1} from the server, or use the python json libary to generate that for you.

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

JQuery has a nice json-reader (I just read the docs, so there might be mistakes in my examples)

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

Javascript:

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

An alternative View suggested by Issy (cute because it follows the DRY principle)

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           

回答by Peter Rowell

Rather than do all this messy, low-level ajax and JSON stuff, consider using the taconite pluginfor jQuery. You just make the call to the backend and it does the rest. It's well-documented and easy to debug -- especially if you are using Firebug with FF.

与其做这些杂乱的、低级的 ajax 和 JSON 的事情,不如考虑使用jQuery的taconite 插件。您只需调用后端,剩下的由它来完成。它有据可查且易于调试——尤其是当您将 Firebug 与 FF 一起使用时。