JS跨域解决方案记录

网上不少方案,包括:

  1. jsonp(最常用)
  2. iframe(限于同根域)
  3. swf辅助
  4. 代理
  5. script标签

在这里特别尝试了一下最后一种方案。
分别配置了www.a.com和www.b.com
www.a.com中index.html代码:

1
2
3
4
5
6
7
8
9
10
11
// javascript 部分
<script type="text/javascript">
$(function () {
    var script = document.createElement("script");
    script.src = "http://www.b.com/script.php";
    script.onload = function () {
        alert(remote.test);
    }
    $("head")[0].appendChild(script);
});
</script>

www.b.com中script.php代码:

1
2
3
<?php
echo "var remote={test:'hello'};";
?>

得到的结果是“hello”。

原文地址:https://www.cnblogs.com/liangle/p/2512529.html