2012-03-27 122 views
0

我想知道我可以使用什麼解決方案來使用js作爲客戶端和PHP作爲api的服務器端的REST api?
我試過使用iFrame,頻道文件和自定義標題。
但沒有人工作。
- 我想知道我該怎麼做。
在此先感謝。與我的REST API相同的來源策略

事情我已經試過不已:
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> 

- >返回任何內容。

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> 

- >返回任何內容。

3)腓標題:

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; 
} 

- >返回任何內容。

目前還沒有工作。

+0

唯一真正的解決方案是託管在您的服務器上的代理服務器將請求服務器端轉發給其他api(jsbin),並返回結果。這也更安全。 – mellamokb 2012-03-27 16:34:47

+0

@mellamokb你確定嗎?因爲這會讓用戶更加困難,那麼facebook js sdk怎麼做呢? – funerr 2012-03-27 16:36:10

+1

我誤解你在做什麼。你爲第三方用戶提供js api?然後你需要JSONP或IFrame嵌入。見http://stackoverflow.com/questions/4007018/why-does-new-facebook-javascript-sdk-not-violate-the-same-origin-policy。 – mellamokb 2012-03-27 16:44:35

回答

0

設置Reverse Proxy會有所幫助。通過使反向代理看起來像請求來自同一臺服務器,可以繞過相同的源策略。