2014-06-13 28 views
1

我有一個HTML文件的代碼誤差與蟒一個Ajax請求

<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' 

任何人都可以請幫我找到錯誤嗎?

+0

您是否嘗試將'data'轉儲到python中的控制檯? – DankMemes

+0

我沒有使用python那麼多,但我認爲如果你把data ['var1'] .value'改成'data.getvalue('var1')'應該是好的 –

+0

@GovindSinghNagarkoti javascript會接受非引號的名字在json中,只要它們是有效的js標識符 – DankMemes

回答

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) 

我希望,我可以幫助與這些職位一些其他p eople!