【问题标题】:sending a JSON object from a Python script to jQuery?将 JSON 对象从 Python 脚本发送到 jQuery?
【发布时间】:2012-04-26 00:43:00
【问题描述】:

我正在尝试将从 .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 状态。真的不知道会发生什么。很抱歉,如果这是显而易见的事情,并提前感谢您提供的帮助。

我尝试使用带有一些尊重 json 格式行的 .txt 文件来执行此操作,并且效果很好。

---------

更新:解决方案

由于我使用的是 Django,它的工作方式与示例略有不同,我的想法并不正确。就这样吧。

JS 文件应该调用你在 URLs.py 上的一些 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')

【问题讨论】:

  • FireFox + FireBug 是我首选的调试组合。控制台选项卡为您提供了所发生事件的详细信息。非常有用。
  • 由于您使用的是 Django,请显示应该为 json 提供服务的实际视图。

标签: jquery python django json getjson


【解决方案1】:

你如何为 getActive.py 提供服务?

您需要一个丰富的网络服务器来为 getActive.py 添加响应标头。 “内容类型”=“应用程序/json。”

【讨论】:

  • 我在使用django轻量级开发Web服务器..会是这个原因吗?
  • 如果你想使用 django 提供 json,使用这个:stackoverflow.com/questions/2428092/…
  • 谢谢@pylover,你是对的,我的错。我这样做是直接调用该脚本,这对 django 不起作用。所以我刚刚在views.py上创建了一个新函数,我从.js调用它,做我想要的并返回一个带有Json信息的httpResponse。加上标题。再次感谢。我终于向前迈进了。我将使用我提出的解决方案编辑我的帖子。
  • 如果它解决了您的问题,请不要忘记将其标记为答案
猜你喜欢
  • 2011-05-17
  • 2018-02-08
  • 2012-06-14
  • 1970-01-01
  • 2019-07-04
  • 2014-09-11
  • 2015-07-07
  • 2014-07-08
  • 2014-07-04
相关资源
最近更新 更多