您的位置:首页 > 编程语言 > Python开发

python+ajax的简单应用

2007-08-24 09:11 567 查看
前几天写了一个程序,想用ajax,看了看,用了一些很简单的东西,贴出来共同学习一下
(有兴趣的话可以访问一下  http://ir.hit.edu.cn/demo/te/

1.首先是xmlhttprequest的创建:

try {
    request = new XMLHttpRequest();
} catch (trymicrosoft) {
       try {
  request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
      try {
  request = new ActiveXObject("Microsoft.XMLHTTP");
       } catch (failed) {
  request = false;
       }
 }
}
if (!request && typeof XMLHttpRequest != 'undefined') {
   request = new XMLHttpRequest();
}
if (!request)
    alert("Error initializing XMLHttpRequest!");

这样可以支持多浏览器
2.然后是和服务器建立链接,发送数据:

request.open("GET", url, true);
request.onreadystatechange = yourfuntion(响应函数);
request.send(null);

3.最后就是响应函数了
首先获取服务器发送来的数据,可以是html,纯文本,也可以是script,下面以html为例:
举例:
如果你的html代码中要用ajax更新一个TEXTAREA里的内容,初始TEXTAREA如下:
<TEXTAREA name="word" rows="13" cols="100" wrap="soft" id="text"></TEXTAREA><br />
更新方法如下:

  function 响应函数() {
       if(xmlhttp.readyState==4) {
            if(xmlhttp.status==200)  {
                document.getElementById("text").innerHTML=xmlhttp.responseText;   
             } else {
           alert("与服务器链接出现错误!");
              }
         }
   }

这样就可以用服务器传来的数据更新TEXTAREA里的内容
举例:
如果你请求的是1.html
那么你的1.html中就是你的TEXTAREA里想要更为为的数据,编码要是UTF-8的

:)至于标题中的python只是服务器上的后台程序。
希望对大家有用! 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息