2013-03-01 126 views
15

我有一個按鈕,一個HTML頁面,我需要執行一個Python腳本,當我們點擊按鈕,返回到相同的HTML頁面的結果。執行按鈕Python腳本點擊

所以我需要對返回值做一些驗證並執行一些操作。

這裏是我的代碼:

HTML:

<input type="text" name="name" id="name"> 
<button type="button" id="home" onclick="validate()" value="checkvalue"></button> 

JS:

function validate(){ 
    if (returnvalue=="test") alert(test) 
    else alert ("unsuccessful") 
} 

什麼我的Python代碼正在做的是對的名稱一些驗證在進入文本框並給出返回狀態。

但我需要在同一頁面上返回結果,所以我可以在稍後提交表單提交所有細節。任何幫助將不勝感激

+0

的Python運行在服務器端,這樣你就可以得到最接近的是AJAX值發送到您的服務器,並返回驗證結果。 – Passerby 2013-03-01 05:31:01

+1

相關:[如何連接Javascript到Python共享數據與JSON格式的兩種方式?](http://stackoverflow.com/questions/11747527/how-to-connect-javascript-to-python-sharing-data-with -json-format-in-both-ways) – jfs 2013-03-01 06:23:04

回答

17

您可以使用Ajax,這是更容易jQuery

$.ajax({ 
    url: "/path/to/your/script", 
    success: function(response) { 
    // here you do whatever you want with the response variable 
    } 
}); 

,你應該閱讀the jQuery.ajax page,因爲它有太多的選擇。

+1

在我的情況下,這段代碼從文件的URL – 2017-06-30 09:19:16

12

做一個頁面(或服務)的蟒蛇,它可以接受郵遞或get請求並處理信息,並返回一個響應。如果響應採用json格式,則會更好。然後,您可以使用此代碼在點擊按鈕上撥打電話。

<input type="text" name="name" id="name"> 
<button type="button" id="home" onclick="validate()" value="checkvalue"> 
<script> 
$('#id').click(function(){ 

$.ajax({ 
     type:'get', 
     url:<YOUR SERVERSIDE PAGE URL>, 
     cache:false, 
     data:<if any arguments>, 
     async:asynchronous, 
     dataType:json, //if you want json 
     success: function(data) { 
     <put your custom validation here using the response from data structure > 
     }, 
     error: function(request, status, error) { 
     <put your custom code here to handle the call failure> 
     } 
    }); 
}); 
</script> 

我希望這有助於

+1

下載python腳本文件非常感謝你..它真的爲我工作 – user2058205 2013-03-01 06:38:54

+0

樂於幫助。如果您不介意,請在答案被接受的情況下標記答案。 – Hari 2016-06-22 18:59:36

+0

@Hari請問$('#id')在做什麼?這裏用'#id'作爲佔位符來代替'home'之類的東西(在OP的問題中)?如果是這樣,我仍然不確定$是在做什麼 – 2016-11-23 13:48:17