通过jQuery AJAX将数据发布到Python CGI脚本 [英] POST data to Python CGI script via jQuery AJAX

查看:227
本文介绍了通过jQuery AJAX将数据发布到Python CGI脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个简单的脚本,其中一些数据使用jQuery .ajax函数发送到Python CGI脚本。 Python脚本只会将数据发布到大写,然后将数据返回到HTML文件,其中div将使用内容进行更新。

I'm trying to setup a simple script where some data is sent using the jQuery .ajax function to a Python CGI script. The Python script would just make the data posted to it uppercase, and then return that data to the HTML file, where a div would be updated with the content.

我有代码如下所示。当我运行它时,执行AJAX调用,但 div没有更新内容。 div没有更新发送的数据。

I have the code shown below. When I run it, the AJAX call executes, but the div is not updated with the content. the div is not updated with the data being sent.

我如何修改此代码,以便根据发送的数据进行更新?

How would I modify this code so that it updates with the data being sent?

我感谢任何帮助。

我的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代码:

My Python Code:

#!/usr/bin/python

import cgi, cgitb 
cgitb.enable() 

data = cgi.FieldStorage()

print "Content-Type: text/html"
print data

编辑:我已将我的代码更新为当前显示的内容,现在文档使用此字符串更新:

FieldStorage(None, None, []) 

如何修改我的代码以便div更新数据?

推荐答案

我认为$ .ajax中的数据应该像键值对的哈希。
尝试:

I believe that the "data" inside the $.ajax should be like a hash of a key-value pairs. try:

$.ajax(
....
  data: {
    a: "aa",
    b: "bb"
  }
...

如果你在div中看到类似的东西:

If you see in the div something like:

MiniFieldStorage('a', 'aa')

然后你应该通过以下方式访问它:

Then you should access it via:

my_param = cgi.getfirst('a')

print "Content-Type: text/html\n"
print my_param

如果它仍然不能正常工作,你可以通过GET而不是POST进行测试吗?
另外,什么是您正在访问的AJAX文件的结构?(是子目录中的文件?等等)

If it's still not working, can you test it via GET instead of POST ? In addition, what's the structure of the AJAX file(s) that you're accessing ? ( is the file inside a sub-directory ? etc... )

这篇关于通过jQuery AJAX将数据发布到Python CGI脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆