[文章+部分代码 作者:张宴 本文版本:v1.0 最后修改:2009.03.09 转载请注明原文链接:http://blog.zyan.cc/ajaxcdr/]

  最近的一个项目中,需要通过 JavaScript 提交表单数据到另一个域名下的PHP接口(因为数据较大,需要HTTP POST方式提交),并获取PHP接口的返回值,在页面无刷新、无跳转的情况下,更新div标签内的内容。

  浏览器出于安全考虑,是不允许JavaScript代码进行跨域操作。JavaScript 和 AJAX 跨域访问分为两大类,一是本域和子域的交互,二是本域和其他域的交互。

  一、本域和子域的交互:www.zyan.cc 和 blog.zyan.cc
  二、本域和其他域的交互:blog.zyan.cc 和 api.bz

  本域和子域的交互,可以通过iframe设置两个域名document.domain = "zyan.cc",实现统一zyan.cc域下的跨域访问。

  本域和其他域的交互,可以通过iframe、代理、JS创建动态脚本等几种方法来实现,这里有篇文章对几种方法作了简要的介绍

  iframe、JS创建动态脚本这两种方法,需要开发者能控制两个域,两端都要编写相应的代码,非常麻烦。在本域服务器上用PHP写个代理中转程序,让本域PHP程序去读取远程其他域的数据再返回给自己,是常用的方法。但是,在本域“前端是CDN或Squid缓存服务器,后端才是PHP应用程序服务器”的系统架构下,穿透CDN或Squid去访问不能被缓存的PHP代理中转程序,效率是很低的。



  国外有人尝试用 Flash 做 JavaScript 和 AJAX 跨域访问中转,无疑是一个好方法。JavaScript 将数据提交给本域下的 Flash,通过 Flash 中转去访问其他域的接口,条件只需要其他域的根目录下有一个crossdomain.xml文件,文件中设置允许所有域名或允许本域访问即可。很多网站的API域名都提供了crossdomain.xml文件。

  例如:
  1、新浪博客的crossdomain.xml文件(http://blog.sina.com.cn/crossdomain.xml)设置了允许所有域名访问;
  2、饭否API的crossdomain.xml文件(http://api.fanfou.com/crossdomain.xml)设置了允许所有域名访问;
  3、校内网API的crossdomain.xml文件(http://api.xiaonei.com/crossdomain.xml)设置了允许所有域名访问;
  4、优酷网的crossdomain.xml文件(http://www.youku.com/crossdomain.xml)设置了允许所有域名访问;
  5、土豆网的crossdomain.xml文件(http://www.tudou.com/crossdomain.xml)设置了允许所有域名访问;

  6、逍遥视频的crossdomain.xml文件(http://v.xoyo.com/crossdomain.xml)设置了只允许*.xoyo.com域名访问;
  7、网易的crossdomain.xml文件(http://www.163.com/crossdomain.xml)设置了只允许tech.163.com、sports.163.com等几个域名访问。



  本人在“Cross-domain AJAX using Flash”的基础上,增加了对表单进行智能处理的功能,封装了一个JavaScript包:AJAXCDR。通过 AJAXCDR,即可轻松地解决 JavaScript 和 AJAX 跨域 HTTP POST/GET 表单请求,支持IE、Firefox、谷歌Chrome等多种浏览器。

  AJAXCDR 拥有两个文件:ajaxcdr.js 和 ajaxcdr.swf,AJAXCDR 拥有一个 JavaScript 函数 AjaxCrossDomainRequest() 和一个全局变量 AjaxCrossDomainResponse。

  一、AJAXCDR 下载:
  http://blog.zyan.cc/demo/ajaxcdr/ajaxcdr-1.0.zip  
  注意:请编辑ajaxcdr.js,查找“/demo/ajaxcdr/ajaxcdr.swf”,将这段Flash文件路径换成您的路径。


  二、AJAXCDR 函数说明:
  1、JavaScript函数:
  AjaxCrossDomainRequest(URL, Method, FormName, CallBack);

  参数说明:
  URL:需要访问的URL地址,相当于表单的action=的值。
  Method:方法,本函数支持POST和GET方法,相当于表单的method=的值。
  FormName:表单名称,相当于表单的name=的值。
  CallBack:回调函数,请求完成后,回调用户的一个函数,用户可以在该函数内对返回值进行处理。

  2、JavaScript全局变量:
  AjaxCrossDomainResponse
  当用户调用AjaxCrossDomainRequest()函数完成 HTTP POST/GET 请求后,该函数会把服务器端返回的数据写入到AjaxCrossDomainResponse变量中,您可以通过AjaxCrossDomainResponse变量获取返回值。


  三、AJAXCDR 应用实例:
  1、实例一(简单演示):
  演示地址: http://blog.zyan.cc/demo/ajaxcdr/demo1.html
  echo.php 源代码为:http://api.bz/ajaxcdr/echo.txt
  crossdomain.xml 文件为:http://api.bz/crossdomain.xml


  2、实例二(复杂表单演示):
  演示地址: http://blog.zyan.cc/demo/ajaxcdr/demo2.html
<html>
<head>
<title>Ajax 跨域 HTTP POST/GET 访问请求演示:Ajax Cross Domain HTTP POST/GET Request Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
<!--
body,td,th {
  font-size: 14px;
}
-->
</style>
</head>
<body>
<form name="cross_domain_demo">
<table width="600" border="1">
  <tr>
    <td colspan="2" align="center" valign="top"><strong>Ajax 跨域 HTTP POST/GET 访问请求演示(鼠标右键查看HTML源代码)</strong></td>
  </tr>
  <tr>
    <td colspan="2" align="center" valign="top">函数说明与下载地址:<a href="http://blog.zyan.cc/ajaxcdr/" target="_blank">http://blog.zyan.cc/ajaxcdr/</a></td>
    </tr>
  <tr>
    <td align="right" valign="top">username</td>
    <td><input name="title" type="text" value="用户名"></td>
  </tr>
  <tr>
    <td align="right" valign="top">password</td>
    <td><input name="password" type="password" value="123456"></td>
  </tr>
  <tr>
    <td align="right" valign="top">content</td>
    <td><textarea name="content" cols="58" rows="5">文本区域值</textarea></td>
  </tr>
  <tr>
    <td align="right" valign="top">city</td>
    <td>
    <select name="city">
        <option value="北京">北京</option>
        <option value="上海">上海</option>
        <option value="深圳">深圳</option>
      </select>  </td>
  </tr>
  <tr>
    <td align="right" valign="top">interest</td>
    <td>
    <select name="interest[]" multiple>
        <option value="玩游戏">玩游戏</option>
        <option value="踢足球">踢足球</option>
        <option value="看书">看书</option>
    <option value="旅游">旅游</option>
    </select>  </td>
  </tr>
  <tr>
    <td align="right" valign="top">gender</td>
    <td>
    <input type="radio" name="gender" value="男">男
      <input type="radio" name="gender" value="女" >女
      <input type="radio" name="gender" value="未知" checked>未知  </td>
  </tr>
  <tr>
    <td align="right" valign="top">grade</td>
    <td>
    <input type="checkbox" name="grade[]" value="等级一">等级一
    <input type="checkbox" name="grade[]" value="等级二">等级二
    <input type="checkbox" name="grade[]" value="等级三">等级三
    <input type="checkbox" name="grade[]" value="等级四">等级四  </td>
  </tr>
  <tr>
    <td align="right" valign="top">publish</td>
    <td><input type="checkbox" name="publish" value="发布">发布</td>
  </tr>
  <tr>
    <td align="right" valign="top">&nbsp;</td>
    <td>
    <a href="javascript:AjaxCrossDomainRequest('http://api.bz/ajaxcdr/echo.php', 'POST', 'cross_domain_demo', 'mycallback(\'参数①\', \'参数②\', myparam)');"><img src="post_button.gif" width="100" height="24" align="absmiddle" border="0"></a>
    &nbsp;&nbsp;  
    <button onClick="AjaxCrossDomainRequest('http://api.bz/ajaxcdr/echo.php', 'GET', 'cross_domain_demo', 'mycallback(\'参数①\', \'参数②\', myparam)'); return false;">GET方式提交</button>
  </td>
  </tr>  
</table>
</form>
<table width="600" border="1">
  <tr>
    <td>JavaScript POST/GET 跨域提交信息到:http://api.bz/ajaxcdr/echo.php (<a href="http://api.bz/ajaxcdr/echo.txt" target="_blank">源代码</a>) </td>
  </tr>
  <tr>
    <td><strong>api.bz服务器端返回信息:</strong></td>
  </tr>
  <tr>
    <td><div id="return_info"></div> </td>
  </tr>
</table>

<script type="text/javascript">
var myparam = "参数③";
function mycallback(param1, param2, param3){
    //提示:AjaxCrossDomainResponse是一个全局变量,它的值为远程服务器的返回值。
    document.getElementById('return_info').innerHTML = "<pre>" + param1 + param2 + param3 + "<BR>" + AjaxCrossDomainResponse + "</pre>";
}
</script>
<script type="text/javascript" src="/demo/ajaxcdr/ajaxcdr.js"></script>
</body>
</html>
  echo.php 源代码为:http://api.bz/ajaxcdr/echo.txt
  crossdomain.xml 文件为:http://api.bz/crossdomain.xml




技术大类 » PHP/JS/Shell | 评论(89) | 引用(0) | 阅读(120284)
通化网络推广 Email Homepage
2011-11-11 17:47
很喜欢flash的
小龙女
2011-12-6 15:06
总是和ajax起冲突还是不太好用
Louis Vuitton Neverfull Email Homepage
2012-4-21 17:45
www.lvbagsclassic.com are authorized authentic Louis Vuitton handbags outlet store. All the items at our site are 100% authentic. All our Louis Vuitton handbags will come with the authenticity card, serial Number, dust bag and care booklet. We promise you will be 100% satisfied when you get such cheap authentic Louis Vuitton handbags from us!
Louis Vuitton Neverfull
Hogan
2012-5-10 18:05
Mentre youre gestione di problemi complessi tra cui PAYE insieme con le imprese del prelievo, l'idea è sicuramente intelligente per acquisire specializzata fare qualcosa di sicuro si sta usando la vostra organizzazione. Self-employmentSelf lavoratori uomini e donne potrebbe anche fare pieno uso Hogan dei ragionieri in tutta Stansted, quando hanno l'effetto della loro prelievo unico e sì, è spesso sconcertante. Stare di fronte a una buona varietà prelievo può essere schiacciante, di conseguenza, il
coach factory outlet Email Homepage
2012-5-17 13:16
Today, following half a century, mentor leather-bases coach factory outlet continues to be the delicate craft of leather-based master is accountable for,Would you like to meet more friends, or go with the times? If yes, coach factory online is opening welcome doors to you.in the market you definitely can find various colorways that are designed in as well as the high quality that applied in. For most of you would like to come. So just come to our coach factory outlet online store to choose one.
louis vuitton sale Email Homepage
2012-5-17 13:16
Louis Vuitton belt at louis vuitton sale is one kind of fashion accessory with high cost performance among the Louis Vuitton accessories.Offering quality LV products with favorable prices, louis vuitton outlet store is at your service. Hurry up, or you can not seize the chance.in fact, louis vuitton is one of the most famous fashion design master.he opened the fist suitcase shop called after his name.
coach outlet online Email Homepage
2012-5-17 13:16
I heard of coach outlet online through the advertisement when I was shopping. And now I often brow the webpage and buy Coach bags online.It is a symbol regarding position not to mention nature.Here I would like to launch a excellent bags pertaining to business men.Which may be coach outlet store.coach outlet has always been simple,durable style features to win consumers.The products are more flexible,with easy bleaching,wear characteristics,and simply use a damp cloth.
coach outlet, Email Homepage
2012-5-17 13:16
Remember the coach outlet provide coach bags which won't be deteriorated into its overall styles by any means. It will maintain its looks, colors, and uniqueness for long time.coach outlet store online has been voted by Hour Detroit magazine readers as the Best of Detroit in their 12th annual readers'poll.Lots of women like which usually amount normally include a coach outlet online ,it provides coziness to many girls that don't even think it is a great bushel of great interest directly to them.
xujie777 Email
2012-5-19 08:54
We aim to make all our customers satisfy with our products. You will find a variety of Men's fashion louis vuitton uk, fashion Women's cheap Louis Vuitton bags in our store at affordable price.Thinking of interesting ways to cost a milestone birthday? louis vuitton online shop had one of the most distinctive distinctive celebrations.bakery along with living room operated by means of about three moment louis vuitton online Most effective Pastry Chef’s of the year Rammy Nominee Chef’s.
xujie777 Email
2012-5-19 08:54
The choices are likely to be basically countless seeing that louis vuitton outlet occurs with the help of completely new and also incredible concepts once in a while.Louis vuitton Wholesale Monogram Canvas HandbagsLouis Vuitton Collection Beach Handbags louis vuitton bags outlet Damier Canvas HandbagsLouis vuitton Mahina HandbagsLouis Vuitton Monogram Mini Lin HandbagsLouis Vuitton Monogram Multicolore HandbagsLouis vuitton Monogram Vernis HandbagsLouis Vuitton Wholesale Epi Leather HandbagsLouis Vuitton For Men HandbagsLouis Vuitton Damier Canvas WalletsLouis Vuitton Epi Leather WalletsLouis Vuitton Monogram Canvas WalletsLouis Vuitton Monogram Vernis WalleLouis Vuitton ShoesLouis Vuitton Men wallets.As the Authentic Louis Vuitton are so high-priced, so came the louis vuitton handbags outlet.
xujie777 Email
2012-5-19 08:54
coach outlet has become a popular shopping experience for consumers around the world, and a desirable distribution channel for manufacturer's and retailers.Getting your hands on coach outlet store online can be a hefty investment of hundreds of dollars.But do not despair,the Coach Outlet store could be the answer to your prayers.coach outlet online is your smart choice when you want to get the discount Coach accessory. You can find the exact Coach Bags and other accessory you want at a low price that's right for you. My dear friends, let the coach outlet online pave your way into the world of high fashion with their ultimate fashion factory.
xujie123
2012-5-21 11:30
Our online store offers you discounted Designer louis vuitton replica wallet at present. You could find them in desirable quality and price. If you don't mind high class louis vuitton uk, have a good time here.louis vuitton Store Online Handbags can also bring great accuracy as well as practical applicability and fashionable.Have you ever dreamed of being as charming as Madonna? Have you ever thought of becoming an envy of all your friends? If so, come to louis vuitton outlet.<br/>
xujie555
2012-5-21 13:57
coach factory outlet uses graceful accessories to match the classical logo of coach, which is the best combination of coach. The handmade coach products?can make you more charming and graceful.coach factory online provides people many coach goods. If you wish to snatch the coach handbag, then this best method is made for that you like for coach discount.coach factory outlet online is a fashion brand to ensure its quality. With designer coach shoulder bags, you will always attract people's attention. The bags will emphasize your personal style and taste.<br/>
xujie333
2012-5-21 15:22
coach outlet online Store guarantee that all the coach handbags offered are own high quality. In addition , all of them are sold at an unexpected low price.If you want to purchase, just visit their website.coach factory outlet is really sizzling kinds of shopping way for you. With the usage of the replica designer coach bags, you can surely be able to change your individual looks in a stunning manner.Coach bags on sale from the coach outlet are cheap or discount prices that you certainly will stand out from the crowd on your next camping trip!<br/>
wkylin
2012-8-17 16:26
你好,现在有一个问题不是很理解,swf文件这个起到一个桥梁的作用,post过去的数据后台如何取到呢??后台是用java来做的??不是php。。现在对这个还是没有完全理解。能加你一下QQ么??QQ:270917337
lbfmin Email Homepage
2012-10-22 10:28
var contentType = "application/x-www-form-urlencoded";
这句设置在flash没起作用,修复这个BUG就完美了,后台接收到参数就不需要再做解析!
老马
2013-3-1 15:40
为什么会用javascript弹出“Flash not loaded” 这个信息的?
blucexiong
2013-10-15 10:49
请问有没有flash的源文件代码?能否发给我邮箱:568483466@qq.com,小弟感激不尽...
objedt Email
2013-11-21 08:15
有的客户机上提示 Flash not loaded  ,但是flash 都装上了。求解。
分页: 4/5 第一页 上页 1 2 3 4 5 下页 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]