如何从Django中输出JSON,并从跨域调用jQuery? [英] How to output JSON from within Django and call it with jQuery from a cross domain?

查看:129
本文介绍了如何从Django中输出JSON,并从跨域调用jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个bookmarklet项目,我试图从我的服务器(这当然是在一个不同的域)运行Django动力系统的jQuery获取JSON数据。

For a bookmarklet project I'm trying to get JSON data using jQuery from my server (which is naturally on a different domain) running a Django powered system.

根据jQuery docs:从jQuery 1.2开始,如果指定JSONP回调,您可以加载位于另一个域上的JSON数据,可以这样做: myurl?callback =?。jQuery自动用正确的方法名替换?来调用,调用你指定的回调函数。例如,我可以使用以下代码片段在Firebug控制台中成功测试它:

According to jQuery docs: "As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback." And for example I can test it successfully in my Firebug console using the following snippet:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&    format=json&jsoncallback=?",
        function(data){
          alert(data.title);
        });

它会将返回的数据打印在警报窗口中,例如最近上传的标记的猫。但是,当我尝试使用我的服务器类似的代码时,我根本没有任何东西:

It prints the returned data in an alert window, e.g. 'Recent uploads tagged cat'. However when I try the similar code with my server I don't get anything at all:

$.getJSON("http://mydjango.yafz.org/randomTest?jsoncallback=?",
        function(data){
          alert(data.title);
        });

没有警报窗口,Firebug状态栏显示从mydjango.yafz.org传输数据。 ..并继续等待。在服务器端我有这个:

There are no alert windows and the Firebug status bar says "Transferring data from mydjango.yafz.org..." and keeps on waiting. On the server side I have this:

def randomTest(request):
    somelist = ['title', 'This is a constant result']
    encoded = json.dumps(somelist)
    response = HttpResponse(encoded, mimetype = "application/json")
    return response

我也没有成功尝试过:

def randomTest(request):
    if request.is_ajax() == True:
        req = {}
        req ['title'] = 'This is a constant result.'
        response = json.dumps(req)
        return HttpResponse(response, mimetype = "application/json")

所以,为了削减一个长的故事:什么是建议的方法从一个Django视图中返回一块数据,并使用jQuery在跨域方式检索它?

So to cut a long story short: what is the suggested method of returning a piece of data from within a Django view and retrieve it using jQuery in a cross domain fashion? What are my mistakes above?

推荐答案

这似乎有效(我忘了处理回调参数!):

This seems to work (I forgot to process the callback parameter!):

服务器端Python / Django代码:

Server-side Python / Django code:

def randomTest(request):
    callback = request.GET.get('callback', '')
    req = {}
    req ['title'] = 'This is a constant result.'
    response = json.dumps(req)
    response = callback + '(' + response + ');'
    return HttpResponse(response, mimetype="application/json")

用于检索此数据的客户端jQuery代码:

Client-side jQuery code to retrieve this data:

$.getJSON("http://mydjango.yafz.org/polls/randomTest?callback=?",
        function(data){
          alert(data.title);
        });

是否有更好的方法来实现相同的效果(更好的方式在Python和Django编码)?

Is there a better way to achieve the same effect (more established way in terms of Python and Django coding)?

这篇关于如何从Django中输出JSON,并从跨域调用jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆