Ajax自动向Python CGI发送信息

0 投票
1 回答
657 浏览
提问于 2025-04-17 18:25

首先,我的服务器只支持Python,不接受其他框架,所以我只能用Python。我在网上找到一个简单的例子,但我对ajax的了解很少,需要一些帮助。首先,我应该使用Python的cgi模块和getvalue来把这个示例的perl代码转换成Python吗?其次,我应该在哪里修改html部分,以便在一定时间间隔内自动重新加载ajax部分,而不是通过按钮提交?

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代码的Python理解(cgi):

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

import cgi

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

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

至少你的回答帮我解决了时间间隔的问题;不过,我还是需要弄清楚Python的部分:我应该在我的Python代码中使用getvalue('w')还是getvalue('word')来获取表单的值,因为我运行代码时总是出错。

1 个回答

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 对象,并且要妥善管理变量,这样就不会出现内存泄漏,确保重复使用同一个对象。
  • 设置一个合理的时间间隔来进行轮询,考虑到服务器的平均响应时间和可能出现的延迟。

希望这些对你有帮助。

撰写回答