Skip to main content
 首页 » 编程设计

jquery之将 JSON 对象从 Python 脚本发送到 jQuery

2025年05月04日8mfryf

我正在尝试将从 .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,这些 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 返回给 JS 以处理它到 View 的 httpResponse。

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

请您参考如下方法:

您如何提供 getActive.py ?

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