Python的AJAX请求错误

1 投票
1 回答
1145 浏览
提问于 2025-04-18 09:40

我有一个 HTML 文件,里面有以下几行代码:

<script>
function ButClick(){
    $.ajax({
        url: "../cgi-bin/test.py",
        type: "POST",
        data: {var1: 'Value 1', var2: 'Value 2'},
        success: function(response){$("#TestDiv").html(response);}
    })
}
</script>

<form><input type='button' onclick="ButClick()" value="Click Me!" /></form>
<div id='TestDiv'></div>

还有一个 Python 3.4 的脚本,文件名是 test.py:

#![...]/custom/bin/python
# -*- coding: iso-8859-15 -*-
import cgi
import cgitb
cgitb.enable()
data=cgi.FieldStorage()
print("Var1-Data lautet: " + data['var1'].value)

我只想在点击按钮时执行一个 ajax 请求。但是我遇到了以下错误:

Traceback (most recent call last):
File "test.py", line 12, in &lt;module&gt;
print("Var1-Data lautet: " + data['var1'].value)
File "[...]/custom/lib/python3.4/cgi.py", line 598, in __getitem__ raise KeyError(key)
KeyError: 'var1'

有没有人可以帮我找出这个错误?

相关问题:

1 个回答

0

现在,我找到了一个解决我问题的方法。我不再使用CGI,而是选择了PHP和Python。虽然这个解决方案不是特别优雅,但它能实现我想要的功能。此外,我还需要执行一些MySQL查询。总的来说,这样做还可以提高整个页面的性能。

我的代码现在看起来是这样的:

index.html

<html>
<head>
<title>TEST</title>
<script src="jquery.js"> </script>
</head>

<body>
<script>
      function ButClick(){
      var TestVar = "'Hallo! This is a test'";
      $.post('test.php',{var:TestVar},function(response) $('#TestDiv').html(response)});
    }
</script>

    <form><input type='button' onclick="ButClick()" value="Click Me!" /></form>
    <div id='TestDiv'></div>  </body>

</body>


</html>

test.php

<?php
$param1=$_POST['var'];
$command="python test.py $param1 $param2";  
$buffer='';
ob_start(); // prevent outputting till you are done
passthru($command);

$buffer=ob_get_contents();

ob_end_clean();

echo "PHP and".$buffer;

?>

test.py

#path to your python interpreter
#!/usr/bin/python   
#sys module to get access to the passed in parameters
import sys
# the first parameters in sys.argv[0] is the path to the current executing python script
param1=sys.argv[1]
PyAnswer="python back: " +param1
# send the result back to php
print (PyAnswer)

我希望通过这篇帖子能帮助到其他一些人!

撰写回答