使用My REST API的同源策略

时间:2012-03-27 16:30:45

标签: php javascript api rest

我想知道我可以使用什么解决方案来使用js作为客户端和php作为api的服务器端的REST api?
我尝试过使用iFrame,频道文件和自定义标题 但没有一个有效 - 我想知道我应该怎么做 提前谢谢。

我已经尝试过的事情:
1)的iFrame:

$(document).ready(function(){

$("#fff").contents().find("#rrr").submit();
})(jQuery);
-------------
<body>
  <p id="hello">Hello World</p>
  <iframe id="fff" src="#">
    hi
    <form id="rrr" action="http://mydomain/rest/rest.php" method="get">
      <input type="text" value="testy" name="check" />
    </form>
  </iframe>
</body>

- &gt;不返回任何内容。

2)频道文件:
服务器上的文件(js):( conjs.js)

 function getDev(callback){

    jQuery.ajax({
        url: 'rest.php',
        type: 'GET',
        data: 'name=John', // or $('#myform').serializeArray()
        success: function(data) { 
            callback('Get completed '+data); 
        }
    });
}
------------------
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
  <script src="http://mydomain/rest/conjs.js"></script>
</head>
<body>
  <p id="hello">Hello World</p>
  <script type="text/javascript">
getDev(function (response) {
    alert(response);
});
</script>
</body>
</html>

- &gt;不返回任何内容。

3)Php标题:

switch ($_SERVER['HTTP_ORIGIN']) {
    case 'http://jsbin.com': case 'https://jsbin.com':
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type');
    break;
}

- &gt;不返回任何内容。

到目前为止没有工作。

1 个答案:

答案 0 :(得分:0)

设置Reverse Proxy会有所帮助。反向代理用于绕过相同的源策略,使其看起来像来自同一服务器的请求。