我正在尝试设置一个简单的脚本,其中一些数据使用 jQuery .ajax 函数发送到 Python CGI 脚本。 Python 脚本只会将发布到它的数据变成大写,然后将该数据返回到 HTML 文件,其中的 div 将用内容更新。
我有下面显示的代码。当我运行它时,AJAX 调用会执行,但是 div 不会更新内容。 div 不会更新正在发送的数据。
我将如何修改此代码以使其随发送的数据更新?
我非常感谢任何帮助。
我的 HTML 代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Python-jQuery Example</title>
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<script>
$(function()
{
$.ajax({
url: "http://localhost/cgi-bin/post.py",
type: "post",
datatype: "html",
data: "here is data",
success: function(response){
$("#div").html(response);
console.log("There is a response");
}
});
});
</script>
</head>
<body>
<div id="div">Default Stuff</div>
</body>
我的 Python 代码:
#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
data = cgi.FieldStorage()
print "Content-Type: text/html"
print data
编辑:我已将我的代码更新为当前显示的内容,现在文档更新为以下字符串:
FieldStorage(None, None, [])
我该如何修改我的代码,以便 div 随发送的数据更新?
最佳答案
我发现数据需要格式化为键值对,如下所示:
$.ajax({
url: "http://localhost/cgi-bin/variousTests/post.py",
type: "POST",
data: {foo: 'bar', bar: 'foo'},
success: function(response){
$("#div").html(response);
}
});
在 Python 脚本中,我使用此代码从 POST 请求中获取数据(如果使用 GET 请求,它的工作方式完全相同):
#!/usr/bin/python
import cgi, cgitb
cgitb.enable() # for troubleshooting
#the cgi library gets vars from html
data = cgi.FieldStorage()
#this is the actual output
print "Content-Type: text/html\n"
print "The foo data is: " + data["foo"].value
print "<br />"
print "The bar data is: " + data["bar"].value
print "<br />"
print data
关于javascript - 通过 jQuery AJAX 将数据发布到 Python CGI 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20723952/