javascript - 通过 jQuery AJAX 将数据发布到 Python CGI 脚本

标签 javascript python jquery cgi

我正在尝试设置一个简单的脚本,其中一些数据使用 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/

相关文章:

javascript - 禁用 React-Native 文本输入选项

python - 在 Python 中添加来自网络抓取的数据

python - 用 pandas 搜索并返回匹配子串的索引

python - 如何使用 Selenium/Python 获取 JavaScript 编写的 html 内容

javascript - 使用 Angular 组件中的 (#myModal).modal ('show' ) 显示 Bootstrap 模态

javascript - 从 JSON 数据按组显示嵌套的 JS 数组到 HTML

javascript - Twilio 聊天输入()不起作用

javascript - PHP JSON header 导致 JSON.parse 出错(使用 jQuery)

javascript - 如何防止在 iOS 和 Android 设备上加载 javascript 和 css 文件?

javascript - 如何设置 .val() 对输入进行单选检查?