繁体   English   中英

从JSON脚本向jQuery发送JSON对象?

[英]sending a JSON object from a Python script to jQuery?

我正在尝试将从.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')

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM