AJAX调用Python时打印脚本而非所需信息
我还是个初学者(请多多包涵),但我遇到了一些困惑。为什么我在进行一个简单的ajax请求时,返回的结果却是实际的脚本,而不是我想要的内容呢?
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(){
$.ajax({
url: "/js/getData.py",
type: "POST",
datatype:"json",
data: {'key':'value','key2':'value2'},
success: function(response){
console.log('Success!!!!');
var data = response;
console.log("response.message: " + response.message);
console.log("response.keys: " + response.keys);
console.log("response.data: " + response.data);
console.log("response: " + response);
//$('#mommy').html(response);
}
});
});
});
</script>
</head>
<body>
<button id="clickme"> click me </button>
<div id="mommy"></div>
</body>
这是我的Python代码:
#!/usr/bin/env python
import sys
import json
import cgi
fs = cgi.FieldStorage()
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")
result = {}
result['success'] = True
result['message'] = "The command Completed Successfully"
result['keys'] = ",".join(fs.keys())
d = {}
for k in fs.keys():
d[k] = fs.getvalue(k)
result['data'] = d
sys.stdout.write(json.dumps(result,indent=1))
sys.stdout.write("\n")
sys.stdout.close()
如果你直接运行getData.py,输出结果是这样的:
Content-Type: application/json
{
"keys": "",
"message": "The command Completed Successfully",
"data": {},
"success": true
}
这是控制台的输出:
"Success!!!!" simple.html:19
"response.message: undefined" simple.html:21
"response.keys: undefined" simple.html:22
"response.data: undefined" simple.html:23
"response: #!/usr/bin/env python
import sys
import json
import cgi
fs = cgi.FieldStorage()
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")
result = {}
result['success'] = True
result['message'] = "The command Completed Successfully"
result['keys'] = ",".join(fs.keys())
d = {}
for k in fs.keys():
d[k] = fs.getvalue(k)
result['data'] = d
sys.stdout.write(json.dumps(result,indent=1))
sys.stdout.write("\n")
sys.stdout.close()
" simple.html:24
1 个回答
1
你的网页服务器没有设置好,不能运行Python脚本,所以它只是把Python脚本的内容当成普通文件(比如html、css、png等)返回给你,而不是执行这个脚本。
让你的服务器能够运行Python脚本的方法会根据你使用的服务器不同而有所变化。你可以查看Python的文档,了解如何在网页上使用Python,开始学习吧!HOWTO Use Python in the Web