2012-07-28 129 views
1

我剛剛測試了一個腳本,我做了。它在Python中。我使用ajax發送請求並嘗試獲取結果。ajax請求到python腳本

function ajaxFunction(){ 
    var ajaxRequest; 
    var e = document.getElementById("ktype"); 
    var ktype = e.options[e.selectedIndex].value; 
    var acookie = document.getElementById("acookie").value; 
alert (ktype +"\n" + acookie); 
    try{ 
     ajaxRequest = new XMLHttpRequest(); 
    } catch (e){ 
     try{ 
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
     } catch (e) { 
      try{ 
       ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
      } catch (e){ 
       return false; 
      } 
     } 
    } 
    ajaxRequest.onreadystatechange = function(){ 
     if (ajaxRequest.readyState < 4){ 
      document.getElementById("resp").innerHTML = "<center><img src='loading.gif' style='max-width:60px; max-height:60px;'></center>"; 
     } 
     if(ajaxRequest.readyState == 4){ 
      document.getElementById("resp").innerHTML = ajaxRequest.responseText; 
     } 
    } 
ajaxRequest.open("POST", "kindle.py", true); 
ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
ajaxRequest.send("amzcookie=" + acookie + "&ktype=" + ktype); 
} 

python腳本使用CGI。沒有像Django這樣的web框架。

當我這樣做的請求它只是打印python文件的內容。沒有代碼被執行。

+1

你能張貼Python代碼? JS並不真正相關。 – Blender 2012-07-28 18:41:53

+0

同上張貼Python代碼。如果您的服務器設置超出了「CGI」的範圍,那麼也會有所幫助。你能否提供一些關於你運行的服務器和配置文件的相關部分的信息? – Thomas 2012-07-28 18:47:52

+0

爲什麼不使用'JQuery'? – cybertextron 2012-07-28 19:00:52

回答

3

您應該使用JQuery爲...而不是寫自己的Ajax請求時,它可以寫成一行:

$.post('link-to-my-python-script',{data}, 
      function(answer){ 
         // process your request here .. 
        }); 

你可以閱讀更多有關在這裏:JqueryPost