使用python的ajax请求出错

时间:2014-06-13 11:37:23

标签: javascript python ajax

我有一个包含以下代码行的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>

我在test.py中有一个Python 3.4脚本:

#![...]/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 :(得分:0)

现在,我发现自己是解决问题的方法。在那里,我不使用CGI,而是使用PHP和Pyton。当然,这个解决方案并不是很优雅,但它可以满足我的需求。另外,我必须执行一些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)

我希望,我可以帮助这些人发布其他人!