2013-03-08 24 views
0

首先,我的服務器不接受任何額外的框架,但蟒蛇,所以我必須堅持下去。我在互聯網上找到了一個簡單的例子。我有很少的Ajax知識,我需要一些幫助。首先,我使用python的cgi模塊和getvalue for「w」將這個示例perl代碼轉換爲python?其次,我應該在哪裏修改html部分來重新加載時間間隔的ajax部分,而不是使用按鈕提交?AJAX發送信息,以自動蟒蛇CGI

HTML:

<html> 
<head> 
<title>Simple Ajax Example</title> 
<script language="Javascript"> 
function xmlhttpPost(strURL) { 
var xmlHttpReq = false; 
var self = this; 
// Mozilla/Safari 
if (window.XMLHttpRequest) { 
    self.xmlHttpReq = new XMLHttpRequest(); 
} 
// IE 
else if (window.ActiveXObject) { 
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); 
} 
self.xmlHttpReq.open('POST', strURL, true); 
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
self.xmlHttpReq.onreadystatechange = function() { 
    if (self.xmlHttpReq.readyState == 4) { 
     updatepage(self.xmlHttpReq.responseText); 
    } 
} 
self.xmlHttpReq.send(getquerystring()); 
} 

function getquerystring() { 
var form  = document.forms['f1']; 
var word = form.word.value; 
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring 
return qstr; 
} 

function updatepage(str){ 
document.getElementById("result").innerHTML = str; 
} 
</script> 
</head> 
<body> 
<form name="f1"> 
<p>word: <input name="word" type="text"> 
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/cgi-bin/simple-ajax- example.cgi")'></p> 
<div id="result"></div> 
</form> 
</body> 
</html> 

CGI第:

#!/usr/bin/perl -w 
use CGI; 

$query = new CGI; 

$secretword = $query->param('w'); 
$remotehost = $query->remote_host(); 

print $query->header; 
print "<p>The secret word is <b>$secretword</b> and your IP is <b>$remotehost</b>.</p>" 
前面的Perl代碼(CGI)的

我的Python解釋:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import cgi 

myform = cgi.FieldStorage() 
recieved = myform.getvalue('word') 

print '<p> Hi mate, %s' % recieved 

至少你的答案幫助我的間隔問題;但是,我仍然需要找出python部分:我應該使用getv從窗體中獲取值alue('w')或getvalue('word')在我的python代碼中,因爲我在運行代碼時不斷收到錯誤信息。

+0

爲什麼使用xmlhttprequest當你有jQuery – 2013-03-08 18:36:15

+0

我對python,html和css有很好的瞭解,但我真的是js和ajax的新手。謝謝你的迴應,但我沒有關於jQuery的任何線索,任何幫助,將不勝感激壽:) – user1433743 2013-03-08 19:09:32

回答

0

我只能回答第二個部分。

骯髒的方式:

只要你</script>結束標籤前:

var inv = setInterval(function() { 
    xmlhttpPost("/cgi-bin/simple-ajax-example.cgi"); 
}, 5000); 

//if you ever want to stop 
//call stopPolling() 
function stopPolling() { 
    clearInterval(inv); 
} 

這是骯髒的,因爲這可能會導致內存泄漏情況,因爲XMLHttpRequest對象實例是在循環內 - 如果你的服務器響應速度比你的間隔計時器慢,你最終可能會創建大量內存佔用對象。

一個更清潔的方式

  • 使用像jQuery庫
  • 如果使用庫是不可行的,第一個代碼爲Ajax對象實例化的功能,具有可變緩存正確,這樣你不最終會發生內存泄漏,並確保您重用相同的對象。
  • 投票有一個合理的間隔時間,考慮到你的服務器的平均響應時間和意外延遲。

希望這會有所幫助。

+0

我編輯我的問題。 – user1433743 2013-03-08 20:16:25