Jquery AJAX发布到Python cgi
可能重复:Jquery AJAX发布到Python cgi,jquery,python,html,ajax,Jquery,Python,Html,Ajax,可能重复: 我已经安装了Apache2,Python正在运行 不过我有个问题。我有两页 一个是Python页面,另一个是带有JQuery的Html页面 我无法将Src发送到googlejquery链接 有人能告诉我如何让我的ajax帖子正常工作吗 $(function() { alert('Im going to start processing'); $.ajax({ url: "saveList.py",
我已经安装了Apache2,Python正在运行 不过我有个问题。我有两页 一个是Python页面,另一个是带有JQuery的Html页面 我无法将Src发送到googlejquery链接 有人能告诉我如何让我的ajax帖子正常工作吗
$(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);
}
});
});
还有Python代码
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);
下面是一个示例html文件和随附的python CGI脚本,应该可以帮助您: 使用此html:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function()
{
$('#clickme').click(function(){
alert('Im going to start processing');
$.ajax({
url: "/scripts/ajaxpost.py",
type: "post",
datatype:"json",
data: {'key':'value','key2':'value2'},
success: function(response){
alert(response.message);
alert(response.keys);
}
});
});
});
</script>
</head>
<body>
<button id="clickme"> click me </button>
</body>
</html>
单击按钮后,您可以看到cgi脚本返回:
{
"keys": "key2,key",
"message": "The command Completed Successfully",
"data": {
"key2": "value2",
"key": "value"
},
"success": true
}
请不要打开您的问题的多个副本。我得到的是未定义的,而不是它应该返回的内容。我得到的是“不受支持的方法(“post”),无论我是在
localhost
还是谷歌云上运行它。在这个示例中,fs=cgi.FieldStorage()也没有给我Ajax“data”参数发送的任何键/值对。我使用了:fs=sys.stdin.read()代替cgi.FieldStorage(),它给出了一个格式字符串:key=value&key2=value2。由此,您可以使用d=dict(fs.split(&)中的item使用item.split(“=”)创建python字典。此外,使用print()比sys.stdout.write()更好,因为print()本身添加了换行符。它还会自动将参数转换为字符串。因此,对于上面python脚本中的最后三行,您只需使用:print(json.dumps(result,indent=1))
{
"keys": "key2,key",
"message": "The command Completed Successfully",
"data": {
"key2": "value2",
"key": "value"
},
"success": true
}