如何从一个Python脚本的jQuery发送一个JSON对象? [英] How can I send a JSON object from a Python script to jQuery?

查看:107
本文介绍了如何从一个Python脚本的jQuery发送一个JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过API和各种资源的看着,但我似乎无法得到使用AJAX Python脚本获取一个JSON对象的窍门。我敢肯定,这个问题是我如何处理JSON对象。

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. I'm sure the issue is with how I'm dealing with the JSON object.

首先,在我的服务器上的Python脚本,我生成和打印JSON数组

First, in a python script on my server, I generate and print a JSON array

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

然后,在一个单独的HTML文件,我尝试像

Then, in a separate html file, I try something like

<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>

但我没有得到任何东西。我敢肯定, data.Price 是错的,但我也pretty的肯定,我应该做的只是印刷<$ C结果的东西,而不是$ C> json.dumps

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

任何帮助是AP preciated!在此先感谢和抱歉,如果这是一个明显的问题。

Any help is appreciated! Thanks in advance, and sorry if this is an obvious question.

推荐答案

在你的情况,你都封装在一个阵列 JSON响应。要访问的价格,你需要访问数据[0] 。您需要采用正确的JSON数据。

In your case you have enclosed the JSON response in an array. To access price you need to access data[0]. You need to structure your JSON data properly.

在你的Python脚本以下更改应该允许您访问 data.Price 。让我知道如果你仍然面临的任何问题。

The following changes in your Python script should allow you to access 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))

这篇关于如何从一个Python脚本的jQuery发送一个JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆