如何从Python脚本向jQuery发送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.
我查看了api和各种资源,但似乎无法使用AJAX从Python脚本中获取JSON对象。我确信问题在于如何处理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
但我什么都没得到。我相信数据。价格是错误的,但我也很确定我应该做一些事情,而不是仅仅打印json.dump的结果。
Any help is appreciated! Thanks in advance, and sorry if this is an obvious question.
任何帮助都是赞赏!提前谢谢,如果这是一个明显的问题,我很抱歉。
2 个解决方案
#1
7
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.
在您的例子中,您将JSON响应包含在一个数组中。要访问价格,需要访问数据[0]。您需要正确地构造JSON数据。
The following changes in your Python script should allow you to access data.Price
. Let me know in case you still face any issues.
Python脚本中的以下更改应该允许您访问data.Price。万一你还有什么问题,请告诉我。
import json
print "Content-type: application/json"
print
response={'Price':54,'Cost':'99'}
print(json.JSONEncoder().encode(response))
更多相关文章
- jquery 如何获取json指定键为指定值的另一个指定键的值,该值还是
- Jquery 传json格式数据到后台,后台反序列化得到一个集合list
- JQuery.AJAX - 我的服务器可以返回一大块数据吗?
- jQuery向服务器请求数据并处理
- jquery datatables-一个数据表中的最大列数
- 前台jquery+ajax向后台请求数据,后台返回json,前台显示
- 使用js和ajax从django服务器检索数据
- 在没有重新设置源选项的情况下,使用x-editable更改select2的数据
- 如何更新jqgrid中的数据值