从Python脚本发送JSON对象到jQuery?

时间:2012-04-13 16:09:37

标签: jquery python django json getjson

我正在尝试将从.py文件打印的Json对象发送到Jquery的getJson方法,但是出了点问题。我从包含无效代码的大项目中做了一些简单的例子。一些帮助将不胜感激!


Html文件:

<html xmlns=" http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request json test</title> 
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script src="/js/json-jquery.js" type="text/javascript"></script> 
</head>
<body>
<a href="#" id="getdata-button">Get JSON Data</a>
<div id="showdata"></div>
</body>
</html>

JS档案:

$(document).ready(function(){
    $('#getdata-button').live('click', function(){
        console.log("echo ")

        $.getJSON("/js/getActive.py", function(data) {
            console.log("echo "+ data)
            $('#showdata').html("<p>item1="+data.item1+"</p>");
        });
    });
});

.py文件:

import json
impact="pedro"
print json.dumps({'item1': impact})

关于问题,它不会在$ .getJSON指令下面打印任何内容。我已经检查了浏览器并找到了脚本并通过http获得了OK状态。真的不知道会发生什么。对不起,如果有明显的事情,请提前感谢您提供的帮助。

我尝试使用.txt文件和一些尊重json格式的行进行此操作,并且工作正常。

----------

更新:解决方案

由于我使用的是Django,它与示例有点不同,我没有直接思考。在这里。

JS文件应调用您在URLs.py上的某个URL,该URL会重定向您在views.py中的某些功能

$(document).ready(function(){ 
    //attach a jQuery live event to the button
    $('#getdata-button').live('click', function(){
        console.log("echo ")

        $.getJSON("teste.html", function(data) {

        console.log("echo "+ data)
            //alert(data); //uncomment this for debug
            //alert (data.item1+" "+data.item2+" "+data.item3); //further debug
            $('#showdata').html("<p>teste="+data.item1+"</p>");
        });
    });
});

然后在views.py中处理您需要的信息,并将带有JSON的httpResponse发送回JS,以将其处理到视图。

def teste(request):
    to_json = {
        "item1": "pedro"
    }
    return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')

1 个答案:

答案 0 :(得分:0)

你如何提供getActive.py?

您需要一个富Web服务器来为getActive.py添加响应标头。 “Content-Type”=“application / json。”