正在加载...
2008-4
18
发表于: 未分类 | 作者: xurenlu
标签:

要解决ajax跨域问题,网上给出的方法有二:
1是构建服务器端的代理。简而言之,就是ajax中调用的实质还是本机的url,而服务器端替js去取回远端地址。
2.利用script标记,生成一个标签。在js加载完成后,再执行后续操作。
就是将原来新建xmlHTTPrequest对象的操作改成了新建script标签的操作.
这里给出一个例子:
#ajah.js

  1. var  Ajah=function(url,varname,handleSuccess,handleFailure){
  2.         /**
  3.         * handleSuccess,handleFailure must be functions
  4.         * */
  5.         script = document.createElement("script");
  6.         script.src=url;
  7.         var handler = function(str)
  8.         {
  9.                 handleSuccess(str);
  10.         }
  11.         script.onload = function()
  12.         {
  13.                 var json=eval(varname);
  14.                 handler(json);
  15.         }
  16.         if(window.ie)
  17.         {
  18.                 script.onreadystatechange = function()
  19.                 {
  20.                         if(script.readyState=='complete'||script.readyState== 'loaded')
  21.                         {
  22.                                 var json=eval(varname);
  23.                                 if(typeof json != 'undefined')
  24.                                 {
  25.                                         handler(json);
  26.                                 }
  27.                         }
  28.                 }
  29.         }
  30.         document.body.appendChild(script);
  31. }

而在网页中应这样调用:
#demo.html

  1. <pre>
  2.         <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
  3. <html>
  4. <head>
  5.   <meta name="generator" content=
  6.   "HTML Tidy for Linux (vers 1 September 2005), see www.w3.org">
  7.  
  8.   <title></title>
  9.         <script src="mootools.js"></script>
  10.         <script src="ajah.js"></script>
  11. </head>
  12.  
  13. <body>
  14. <script>
  15. var ajah=new Ajah("data.js","json198",function(str){
  16.         console.debug("returned:");
  17.         console.debug(str);
  18. },
  19. function(str){});
  20. </script>
  21. </body>
  22. </html>
  23. </pre>

被调用的数据文件如下
#data.js

  1. var json198="hello,this is json198";

funciton Ajah(url,varname,handleSuccess,handleFailure){…}
Ajah这个构造函数调用四个参数:
url:远端地址
varname:远端返回数据的变量名
handleSuccess:加载完毕后加载的函数
handleFailure:暂时没用上

: http://www.162cm.com/archives/621.html

本文相关评论 - 1条评论都没有呢

还没有评论。