簡體   English   中英

使用 AJAX 加載跨域端點

[英]Loading cross-domain endpoint with AJAX

我正在嘗試使用 AJAX 加載跨域 HTML 頁面,但除非數據類型為“jsonp”,否則我無法獲得響應。 然而,使用 jsonp 瀏覽器需要一個腳本 mime 類型,但接收“text/html”。

我的請求代碼是:

$.ajax({
    type: "GET",
    url: "http://saskatchewan.univ-ubs.fr:8080/SASStoredProcess/do?_username=DARTIES3-2012&_password=P@ssw0rd&_program=%2FUtilisateurs%2FDARTIES3-2012%2FMon+dossier%2Fanalyse_dc&annee=2012&ind=V&_action=execute",
    dataType: "jsonp",
}).success( function( data ) {
    $( 'div.ajax-field' ).html( data );
});

有什么辦法可以避免在請求中使用 jsonp 嗎? 我已經嘗試過使用 crossDomain 參數,但是沒有用。

如果沒有,有沒有辦法在 jsonp 中接收 html 內容? 目前,控制台在 jsonp 回復中說“意外 <”。

jQuery Ajax 注釋

  • 由於瀏覽器安全限制,大多數Ajax請求都遵循同源策略 請求無法從不同的域、子域、端口或協議成功檢索數據。
  • 腳本和 JSONP 請求不受同源策略限制。

有一些方法可以克服跨域障礙:

有一些插件可以幫助處理跨域請求:

當心!

解決這個問題的最好方法是在后端創建自己的代理,這樣您的代理將指向其他域中的服務,因為在后端不存在同源策略限制。 但是如果你在后端不能這樣做,那么請注意以下提示。


**警告!**

使用第三方代理並不是一種安全的做法,因為它們可以跟蹤您的數據,因此它可以用於公共信息,但絕不能用於私人數據。


下面顯示的代碼示例使用jQuery.get()jQuery.getJSON() ,兩者都是jQuery.ajax() 的速記方法


任何地方的 CORS

2021 更新

公共演示服務器 (cors-anywhere.herokuapp.com) 將在 2021 年 1 月 31 日非常有限

CORS Anywhere (cors-anywhere.herokuapp.com) 的演示服務器旨在作為該項目的演示。 但是濫用已經變得如此普遍,以至於托管演示的平台 (Heroku) 要求我關閉服務器,盡管努力打擊濫用。 由於濫用及其流行,停機時間變得越來越頻繁。

為了解決這個問題,我將進行以下更改:

  1. 速率限制將從每小時 200 次降至每小時 50 次。
  2. 到 2021 年 1 月 31 日,cors-anywhere.herokuapp.com 將停止作為開放代理服務。
  3. 從 2 月 1 日起。 2021 年,cors-anywhere.herokuapp.com 將僅在訪問者完成挑戰后才提供請求:用戶(開發者)必須訪問 cors-anywhere.herokuapp.com 上的頁面以臨時解鎖其瀏覽器的演示。 這允許開發人員試用該功能,以幫助決定自托管或尋找替代方案。

CORS Anywhere 是一個node.js 代理,它將 CORS 標頭添加到代理請求中。
要使用 API,只需在 URL 前面加上 API URL。 (支持https :見github 倉庫

如果您想在需要時自動啟用跨域請求,請使用以下代碼段:

 $.ajaxPrefilter( function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? 'http:' : 'https:'); options.url = http + '//cors-anywhere.herokuapp.com/' + options.url; //options.url = "http://cors.corsproxy.io/url=" + options.url; } }); $.get( 'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing', function (response) { console.log("> ", response); $("#viewer").html(response); });

無論起源

無論Origin跨域jsonp訪問。 這是anyorigin.com 的開源替代

要從google.com獲取數據您可以使用以下代碼段:

 // It is good specify the charset you expect. // You can use the charset you want instead of utf-8. // See details for scriptCharset and contentType options: // http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings $.ajaxSetup({ scriptCharset: "utf-8", //or "ISO-8859-1" contentType: "application/json; charset=utf-8" }); $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?', function (data) { console.log("> ", data); //If the expected response is text/plain $("#viewer").html(data.contents); //If the expected response is JSON //var response = $.parseJSON(data.contents); });

CORS 代理

CORS 代理是一個簡單的node.js 代理,用於為任何網站啟用 CORS 請求。 它允許您站點上的 javascript 代碼訪問其他域上的資源,這些域通常由於同源策略而被阻止。

它是如何工作的? CORS 代理利用跨源資源共享,這是與 HTML 5 一起添加的一項功能。服務器可以指定他們希望瀏覽器允許其他網站請求他們托管的資源。 CORS 代理只是一個 HTTP 代理,它向響應添加一個標頭,說“任何人都可以請求這個”。

這是實現目標的另一種方式(參見www.corsproxy.com )。 您所要做的就是去掉http://www。 來自被代理的 URL,並在 URL 前面加上www.corsproxy.com/

 $.get( 'http://www.corsproxy.com/' + 'en.wikipedia.org/wiki/Cross-origin_resource_sharing', function (response) { console.log("> ", response); $("#viewer").html(response); });

CORS 代理瀏覽器

最近我發現了這個,它涉及各種面向安全的跨域遠程共享實用程序。 但它是一個以 Flash 作為后端的黑匣子。

您可以在這里看到它的實際效果: CORS 代理瀏覽器
在 GitHub 上獲取源代碼: koto/cors-proxy-browser

您可以使用 Ajax-cross-origin 一個 jQuery 插件。 使用此插件,您可以使用jQuery.ajax()跨域。 它使用 Google 服務來實現這一點:

AJAX Cross Origin 插件使用 Google Apps Script 作為代理 jSON getter,其中未實現 jSONP。 當您將 crossOrigin 選項設置為 true 時,插件會用 Google Apps 腳本地址替換原始 url,並將其作為編碼的 url 參數發送。 Google Apps Script 使用 Google Servers 資源獲取遠程數據,並將其作為 JSONP 返回給客戶端。

使用非常簡單:

    $.ajax({
        crossOrigin: true,
        url: url,
        success: function(data) {
            console.log(data);
        }
    });

您可以在此處閱讀更多信息: http : //www.ajax-cross-origin.com/

如果外部站點不支持 JSONP 或 CORS,您唯一的選擇是使用代理。

在您的服務器上構建一個請求該內容的腳本,然后使用 jQuery ajax 在您的服務器上運行該腳本。

只要把它放在你的 PHP 頁面的標題中,它就不會在沒有 API 的情況下工作:

header('Access-Control-Allow-Origin: *'); //allow everybody  

或者

header('Access-Control-Allow-Origin: http://codesheet.org'); //allow just one domain 

或者

$http_origin = $_SERVER['HTTP_ORIGIN'];  //allow multiple domains

$allowed_domains = array(
  'http://codesheet.org',
  'http://stackoverflow.com'
);

if (in_array($http_origin, $allowed_domains))
{  
    header("Access-Control-Allow-Origin: $http_origin");
}

我發布這個以防有人面臨我現在面臨的同樣問題。 我有一台 Zebra 熱敏打印機,配備了 ZebraNet 打印服務器,它提供基於 HTML 的用戶界面,用於編輯多個設置、查看打印機的當前狀態等。我需要獲取打印機的狀態,該狀態顯示在其中一個 html 頁面中,由 ZebraNet 服務器提供,例如,alert() 向瀏覽器中的用戶發送消息。 這意味着我必須首先在 Javascript 中獲取該 html 頁面。 盡管打印機位於用戶 PC 的 LAN 內,但同源策略仍然牢牢地擋住了我的路。 我嘗試了 JSONP,但服務器返回 html,我還沒有找到修改其功能的方法(如果可以,我已經設置了魔術頭 Access-control-allow-origin:*)。 所以我決定用 C# 編寫一個小的控制台應用程序。 它必須以管理員身份運行才能正常工作,否則它會引發 :D 異常。 這是一些代碼:

// Create a listener.
        HttpListener listener = new HttpListener();
        // Add the prefixes.
        //foreach (string s in prefixes)
        //{
        //    listener.Prefixes.Add(s);
        //}
        listener.Prefixes.Add("http://*:1234/"); // accept connections from everywhere,
        //because the printer is accessible only within the LAN (no portforwarding)
        listener.Start();
        Console.WriteLine("Listening...");
        // Note: The GetContext method blocks while waiting for a request. 
        HttpListenerContext context;
        string urlForRequest = "";

        HttpWebRequest requestForPage = null;
        HttpWebResponse responseForPage = null;
        string responseForPageAsString = "";

        while (true)
        {
            context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            urlForRequest = request.RawUrl.Substring(1, request.RawUrl.Length - 1); // remove the slash, which separates the portNumber from the arg sent
            Console.WriteLine(urlForRequest);

            //Request for the html page:
            requestForPage = (HttpWebRequest)WebRequest.Create(urlForRequest);
            responseForPage = (HttpWebResponse)requestForPage.GetResponse();
            responseForPageAsString = new StreamReader(responseForPage.GetResponseStream()).ReadToEnd();

            // Obtain a response object.
            HttpListenerResponse response = context.Response;
            // Send back the response.
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseForPageAsString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            response.AddHeader("Access-Control-Allow-Origin", "*"); // the magic header in action ;-D
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            // You must close the output stream.
            output.Close();
            //listener.Stop();

用戶所需要做的就是以管理員身份運行該控制台應用程序。 我知道這太……令人沮喪和復雜,但它是域策略問題的一種解決方法,以防您無法以任何方式修改服務器。

編輯:從js我做了一個簡單的ajax調用:

$.ajax({
                type: 'POST',
                url: 'http://LAN_IP:1234/http://google.com',
                success: function (data) {
                    console.log("Success: " + data);
                },
                error: function (e) {
                    alert("Error: " + e);
                    console.log("Error: " + e);
                }
            });

請求頁面的 html 被返回並存儲在data變量中。

要通過使用 jherax 建議的本地代理傳遞來獲取外部站點的數據,您可以創建一個 php 頁面,從相應的外部 url 為您獲取內容,然后向該 php 頁面發送 get 請求。

var req = new XMLHttpRequest();
req.open('GET', 'http://localhost/get_url_content.php',false);
if(req.status == 200) {
   alert(req.responseText);
}

作為 php 代理,您可以使用https://github.com/cowboy/php-simple-proxy

這些天您的URL不起作用,但您的代碼可以使用此有效解決方案進行更新:

 var url = "http://saskatchewan.univ-ubs.fr:8080/SASStoredProcess/do?_username=DARTIES3-2012&_password=P@ssw0rd&_program=%2FUtilisateurs%2FDARTIES3-2012%2FMon+dossier%2Fanalyse_dc&annee=2012&ind=V&_action=execute"; url = 'https://google.com'; // TEST URL $.get("https://images"+~~(Math.random()*33)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=" + encodeURI(url), function(data) { $('div.ajax-field').html(data); });
 <div class="ajax-field"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您需要 CORS 代理,它將您的請求從您的瀏覽器代理到具有適當CORS 標頭的請求服務。 此類服務的列表在下面的代碼片段中。 您還可以運行提供的代碼片段以查看從您所在位置對此類服務的 ping。

 $('li').each(function() { var self = this; ping($(this).text()).then(function(delta) { console.log($(self).text(), delta, ' ms'); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.rawgit.com/jdfreder/pingjs/c2190a3649759f2bd8569a72ae2b597b2546c871/ping.js"></script> <ul> <li>https://crossorigin.me/</li> <li>https://cors-anywhere.herokuapp.com/</li> <li>http://cors.io/</li> <li>https://cors.5apps.com/?uri=</li> <li>http://whateverorigin.org/get?url=</li> <li>https://anyorigin.com/get?url=</li> <li>http://corsproxy.nodester.com/?src=</li> <li>https://jsonp.afeld.me/?url=</li> <li>http://benalman.com/code/projects/php-simple-proxy/ba-simple-proxy.php?url=</li> </ul>

弄清楚了。 用這個代替。

$('.div_class').load('http://en.wikipedia.org/wiki/Cross-origin_resource_sharing #toctitle');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM