当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 解决ajax跨域问题的实例

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 解决ajax跨域问题的实例


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 192 ::
收藏到网摘: n/a

要解决ajax跨域问题,网上给出的方法有二:

1是构建服务器端的代理。简而言之,就是ajax中调用的实质还是本机的url,而服务器端替js去取回远端地址。

2.利用script标记,生成一个标签。在js加载完成后,再执行后续操作。

就是将原来新建xmlHTTPrequest对象的操作改成了新建script标签的操作.

这里给出一个例子:

#ajah.js

var  Ajah=function(url,varname,handleSuccess,handleFailure){
        /**
        * handleSuccess,handleFailure must be functions
        * */
        script = document.createElement("script");
        script.src=url;
        var handler = function(str)
        {
                handleSuccess(str);
        }
        script.onload = function()
        {
                var json=eval(varname);
                handler(json);
        }
        if(window.ie)
        {
                script.onreadystatechange = function()
                {
                        if(script.readyState=='complete'||script.readyState== 'loaded')
                        {
                                var json=eval(varname);
                                if(typeof json != 'undefined')
                                {
                                        handler(json);
                                }
                        }
                }
        }
        document.body.appendChild(script);
}

而在网页中应这样调用:

#demo.html

<pre>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux (vers 1 September 2005), see www.w3.org">
 
  <title></title>
        <script src="mootools.js"></script>
        <script src="ajah.js"></script>
</head>
 
<body>
<script>
var ajah=new Ajah("data.js","json198",function(str){
        console.debug("returned:");
        console.debug(str);
},
function(str){});
</script>
</body>
</html>
</pre>

被调用的数据文件如下

#data.js

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