如何将Python脚本中的JSON对象发送到jQuery?

Par*_*ker 5 python ajax jquery json getjson

我查看了API和各种资源,但我似乎无法使用AJAX从Python脚本中获取JSON对象.我确定问题在于我如何处理JSON对象.

首先,在我的服务器上的python脚本中,我生成并打印一个JSON数组

import json
print "Content-type: application/json"
print 
print json.dumps(['Price',{'Cost':'99'}])
Run Code Online (Sandbox Code Playgroud)

然后,在一个单独的html文件中,我尝试类似的东西

<body>
<div id="test">
</div>

<script>
 $(document).ready(function() {
  $.getJSON("http://www.example.com/cgi-bin/makeJSON.py", function(data) {
        $('#test').html("JSON Data: " + data.Price);
    });
});
</script>
</body>
Run Code Online (Sandbox Code Playgroud)

但我什么都没得到.我确定这data.Price是错的,但我也很确定我应该做的事情而不仅仅是打印结果json.dumps

任何帮助表示赞赏!在此先感谢,如果这是一个明显的问题,对不起.

Phi*_*lar 8

在您的情况下,您已将JSON响应括起来了array.要访问您需要访问的价格data[0].您需要正确构建JSON数据.

您的Python脚本中的以下更改应允许您访问data.Price.如果您仍然遇到任何问题,请与我联系.

   import json
   print "Content-type: application/json"
   print 
   response={'Price':54,'Cost':'99'}
   print(json.JSONEncoder().encode(response))
Run Code Online (Sandbox Code Playgroud)