我正在尝试设置一个简单的脚本,其中使用 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 中的“数据”应该像一个键值对的散列。
尝试:
$.ajax(
....
data: {
a: "aa",
b: "bb"
}
...
如果您在 div 中看到类似:
MiniFieldStorage('a', 'aa')
然后你应该通过以下方式访问它:
my_param = cgi.getfirst('a')
print "Content-Type: text/html\n"
print my_param
如果它仍然无法正常工作,您可以通过 GET 而不是 POST 来测试它吗?
此外,您正在访问的 AJAX 文件的结构是什么? (是子目录中的文件吗?等等...)
关于javascript - 通过 jQuery AJAX POST 数据到 Python CGI 脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20723952/