2013-04-05 226 views
1

如何將JSON數據作爲URL字符串發佈到外部URL(跨域)並繞過訪問控制?將JSON數據發佈到外部URL

這裏是一個jQuery阿賈克斯POST請求將無法工作發送給因外部URL訪問控制允許來源:

var json = JSON.stringify(object); 

$.ajax({ 
    type: 'POST', 
    url: externalurl, 
    data: json, 
    dataType: 'json', 
    success: function(data){console.log(data);}, 
    failure: function(errMsg) { 
     console.log(errMsg); 
    }, 
}); 

我收到了一個建議,POST數據到相同的域名,並將「請求傳遞給」外部域名,儘管此解決方案對我來說沒有意義。我正在尋找最安全的解決方案。任何幫助將非常感激。

+0

您是否嘗試過使用JSON-P?我相信在jQuery中,您使用'jsonp'而不是'json'來處理數據類型,但我不是100%確定的... – 2013-04-05 00:34:49

+1

當您說'傳遞請求'解決方案對於你的意思只是你不理解它,希望得到解釋,或者你明白它,但認爲它不適合你目前的情況? @MarkOrmston - JSONP確實可以解決域問題,但只有在設置了外部域來處理它並提供適當的解決方案時,它纔會起作用。 – nnnnnn 2013-04-05 00:37:24

+0

是的,它不適合在這種情況下,數據必須作爲json發送。我也無法控制外部服務器,因此CORS也不是一個可行的解決方案。 – jverban 2013-04-05 00:39:40

回答

2

一種方法繞過同源策略是使用捲曲做實際發射。

我將舉一個使用PHP的例子,但您可以輕鬆地在任何服務器端語言上執行此操作。

設置一個腳本,您的服務器上,例如send.php

首先你點你的阿賈克斯send.php

var json = JSON.stringify(object); 

$.ajax({ 
    type: 'POST', 
    url: send.php, 
    data: json, 
    dataType: 'json', 
    success: function(data){console.log(data);}, 
    failure: function(errMsg) { 
     console.log(errMsg); 
    }, 
}); 

然後你的PHP腳本來轉發:

<?php 
    // Initialize curl 
    $curl = curl_init(); 

    // Configure curl options 
    $opts = array(
     CURLOPT_URL    => $externalscriptaddress, 
     CURLOPT_RETURNTRANSFER => true, 
     CURLOPT_CUSTOMREQUEST => 'POST', 
     CURLOPT_POST   => 1, 
     CURLOPT_POSTFIELDS  => 'field1=arg1&field2=arg2' 
    ); 

    // Set curl options 
    curl_setopt_array($curl, $opts); 

    // Get the results 
    $result = curl_exec($curl); 

    // Close resource 
    curl_close($curl); 

    echo $result; 
?> 
+0

也感謝您的解決方案。這已經成功了! – jverban 2013-04-07 23:55:27

+0

很高興能提供幫助,如果您對解決方案感到滿意,請將其標記爲未來其他人看到的答案。 – 2013-04-08 00:03:33

+0

要接受答案,您可以點擊upvote旁邊的勾號,它會將答案標記爲正確的答案,並且如果您的第一個問題標記爲答案,也會給您一些聲譽:) – 2013-04-08 00:30:32

3

我不久前在PHP中做了這個。這是一個「傳遞請求」的例子。 (您需要啓用PHP捲曲,這與大多數的安裝非常標準。)

<?php 
    //Get the JSON data POSTed to the page 
    $request = file_get_contents('php://input'); 

    //Send the JSON data to the right server 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, "http://location_of_server.com/"); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8")); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request); 
    $data = curl_exec($ch); 
    curl_close($ch); 

    //Send the response back to the Javascript code 
    echo $data; 
?> 
+0

+1比我快:D – 2013-04-05 01:16:00

+0

非常感謝您的解決方案。 – jverban 2013-04-07 23:43:48