Skip to content

2014 03 29 前端跨域POST数据

zhangnan05 edited this page Sep 2, 2014 · 1 revision

layout: page title: 前端跨域POST提交解决方案

{% include JB/setup %}

###前言

咱们说的跨域POST提交解决方案,注意这里是POST提交数据,比如表单提交,所以这时候别跟我说SCRIPT标签实现JSONP什么的。 想要实现POST提交数据无非2种:

  • 1、是服务端允许你跨域。
  • 2、其实就是想办法和需要跨的域名下的页面通信。

conan

1、跨域资源共享

2、postMessage跨域

  • 这个也不做讨论,同理去搜索一下postMessage就可以得到答案了。
  • 缺点也是部分浏览器不支持

3、iframe跨域POST提交数据

需求:

页面a.html在域名a.com下需要提交到域名b.com下

思路:
  • 思路是在a.html里面提交form表单到一个iframe上

  • 让iframe去post你要发送的数据。

  • 等结果出来以后,再重定向(location)到a.com域名下的c.html下,且带上query包含着回调的结果.

  • 这时候iframe里面的内容就是c.html,而它是a.com域名的页面,和a.html是同域,就可以调用parent的方法了。

    简而言之,通过iframe来POST提交数据,通过query来get回调结果.

a.html

<iframe src="" frameborder="0" id="ts"></iframe>
<form action="http://127.0.0.1/Dropbox/code/test/b.php" target="ts" method="post" >
  <input type="text"><br/>
  <input type="password" name="id"></br>
  <input type="submit" value="提交" name="ps">
</form>
<script>
 callback = function(data){
  window.console && window.console.log(data) === undefined || alert(data);
 }
</script>

b.php

  //do some things;
  // ... ...judge user of password
  ///////
  //我这里本地测试修改了host
  header('location: http://zhangnan.baidu.com/Dropbox/code/test/c.html?user='.$_POST['id'] .'&password='. $_POST['ps']);

c.html

<script>
top.callback && top.callback(location.search);
</script>

Clone this wiki locally