201507152326_《Javascript实现跨域有4种方法——介绍jsonp和html5方法》

一. jsonp方法

1. 原理

在js中,我们直接用XMLHttpRequest请求不同域上的数据时,是不可以的。但是,在页面上引入不同域上的js脚本文件却是可以的。

2. 格式

<script>

  function doSomething(jsondata) {

    //todo

};

</script>

<script>http://example.com/data.php?callback=doSomething</script>

 

二. 使用HTML5中新引进的window.postMessage方法来跨域传送数据

1. 获取window对象。 例如:var winObj = element.contentWindow;

2. 格式

//a.html

<script>

function onload() {

  var iframe = document.getElementById('iframe');

     var winObj = iframe .contentWindow;

  winObj .postMessage('哈哈,我是来自页面a的消息','*');

}

</script>

<iframe>id = "iframe" src = "http://www.test.com/b.html"  onload="onload()"</iframe>

 

//b.html

<script>

  window.onmessage = function(e) {

    e = e || event;

    alert(e.data);  // postMessage()方法存储在了data里了

}

</script>

 

posted @ 2015-07-16 00:04  Coca-code  阅读(284)  评论(0编辑  收藏  举报