帖子JSON到Python CGI [英] Post JSON to Python CGI
问题描述
我有安装的Apache2和Python的工作。
我虽然有一个问题。我有两页。
一个Python的页面和其它的HTML页面的JQuery
有人能告诉我怎样才能让我的阿贾克斯后才能正常工作。
< HTML>
< HEAD>
< /头>
<身体GT;
<脚本>
$(函数()
{
警报(我就要开始处理');
$阿贾克斯({
网址:saveList.py
类型:后,
数据:{参数:{你好:世界}},
数据类型:应用/ JSON
成功:函数(响应)
{
警报(响应);
}
});
});
< / SCRIPT>
< /身体GT;
< / HTML>
和Python的code
进口SYS
进口JSON
高清指数(REQ):
结果= {成功:真,信息:成功完成命令'};
数据= sys.stdin.read();
myjson = json.loads(数据);
返回STR(myjson);
OK,让我们看一下你的更新的问题。
首先,你应该通过Ajax的数据属性字符串重新presentation。然后,因为你混的dataType
和的contentType
属性中,更改的dataType
值JSON
:
$。阿贾克斯({
网址:saveList.py
类型:后,
数据:JSON.stringify({'参数':{你好:世界}}),
数据类型:JSON,
成功:函数(响应){
警报(响应);
}
});
最后,修改codeA位使用JSON请求的工作方式如下:
#!的/ usr / bin中/蟒蛇
进口SYS,JSON
结果= {成功:真,信息:成功完成命令'};
myjson = json.load(sys.stdin)
#做些什么myjson对象
打印内容类型:应用程序/ JSON \ñ\ N'
打印json.dumps(结果)#或传入json.dump(结果,sys.stdout替换)
其结果是,在成功
处理的Ajax请求,您将收到对象成功
和的消息
属性。
I have got Apache2 Installed and Python working.
I am having a problem though. I have two pages.
One a Python Page and the other an Html Page with JQuery
Can someone please tell me how I can get my ajax post to work correctly.
<html>
<head>
</head>
<body>
<script>
$(function()
{
alert('Im going to start processing');
$.ajax({
url: "saveList.py",
type: "post",
data: {'param':{"hello":"world"}},
dataType: "application/json",
success : function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
And the Python Code
import sys
import json
def index(req):
result = {'success':'true','message':'The Command Completed Successfully'};
data = sys.stdin.read();
myjson = json.loads(data);
return str(myjson);
OK, let's move to your updated question.
First, you should pass Ajax data property in string representation. Then, since you mix dataType
and contentType
properties, change dataType
value to "json"
:
$.ajax({
url: "saveList.py",
type: "post",
data: JSON.stringify({'param':{"hello":"world"}}),
dataType: "json",
success: function(response) {
alert(response);
}
});
Finally, modify your code a bit to work with JSON request as follows:
#!/usr/bin/python
import sys, json
result = {'success':'true','message':'The Command Completed Successfully'};
myjson = json.load(sys.stdin)
# Do something with 'myjson' object
print 'Content-Type: application/json\n\n'
print json.dumps(result) # or "json.dump(result, sys.stdout)"
As a result, in the success
handler of Ajax request you will receive object with success
and message
properties.
这篇关于帖子JSON到Python CGI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!