简体   繁体   English

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

[英]How can I send a JSON object from a Python script to jQuery?

I've looked through APIs and all sorts of resources, but I can't seem to get the hang of fetching a JSON object from a Python script using AJAX. 我查看了API和各种资源,但我似乎无法使用AJAX从Python脚本中获取JSON对象。 I'm sure the issue is with how I'm dealing with the JSON object. 我确定问题在于我如何处理JSON对象。

First, in a python script on my server, I generate and print a JSON array 首先,在我的服务器上的python脚本中,我生成并打印一个JSON数组

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

Then, in a separate html file, I try something like 然后,在一个单独的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>

But I don't get anything. 但我什么都没得到。 I'm sure that data.Price is wrong, but I'm also pretty certain that I should be doing something instead of just printing the results of json.dumps 我确定data.Price是错误的,但我也很确定我应该做的事情而不仅仅是打印json.dumps的结果

Any help is appreciated! 任何帮助表示赞赏! Thanks in advance, and sorry if this is an obvious question. 在此先感谢,如果这是一个明显的问题,对不起。

In your case you have enclosed the JSON response in an array . 在您的情况下,您已将JSON响应包含在array To access price you need to access data[0] . 要访问价格,您需要访问data[0] You need to structure your JSON data properly. 您需要正确构建JSON数据。

The following changes in your Python script should allow you to access data.Price . Python脚本中的以下更改应允许您访问data.Price Let me know in case you still face any issues. 如果您仍然遇到任何问题,请告诉我。

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

Please provide more context to what you're trying to do. 请提供更多关于您要做的事情的背景信息。 Can you just hard-code the JSON object into the HTML? 你能把JSON对象硬编码到HTML中吗? Or, are you trying to do something more dynamic, like AJAX? 或者,你是否正在尝试做一些更有活力的事情,比如AJAX?

For the former, view the HTML source of the page that Python generates. 对于前者,查看Python生成的页面的HTML源代码。 It must look something like: 它必须看起来像:

<script type="text/javascript">
   var MY_GLOBAL_JSON_OBJECT = { ... };
</script>

Or you could just spit out the JSON object inside the function that's actually using it instead of assigning it first to a global variable. 或者你可以在实际使用它的函数中吐出JSON对象,而不是先将它分配给全局变量。

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

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