使用jQuery AJAX加载跨域端点

时间:2022-04-06 04:51:03

I'm trying to load a cross-domain HTML page using AJAX but unless the dataType is "jsonp" I can't get a response. However using jsonp the browser is expecting a script mime type but is receiving "text/html".

我正在尝试使用AJAX加载跨域HTML页面,但是除非数据类型是“jsonp”,否则我无法得到响应。然而,使用jsonp,浏览器期望得到一个脚本mime类型,但接收的是“文本/html”。

My code for the request is:

我的要求是:

$.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 );
});

Is there any way of avoiding using jsonp for the request? I've already tried using the crossDomain parameter but it didn't work.

有什么方法可以避免对请求使用jsonp吗?我已经尝试过使用跨域参数,但它不起作用。

If not is there any way of receiving the html content in jsonp? Currently the console is saying "unexpected <" in the jsonp reply.

如果没有,有没有办法接收jsonp中的html内容?目前控制台在jsonp回复中显示“unexpected <”。

8 个解决方案

#1


197  

jQuery Ajax Notes

  • Due to browser security restrictions, most Ajax requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
  • 由于浏览器安全限制,大多数Ajax请求都遵循相同的源策略;请求不能成功地从不同的域、子域、端口或协议中检索数据。
  • Script and JSONP requests are not subject to the same origin policy restrictions.
  • 脚本和JSONP请求不受相同的源策略限制。

There are some ways to overcome the cross-domain barrier:

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

There are some plugins that help with cross-domain requests:

有一些插件可以帮助跨域请求:

Heads up!

小心!

The best way to overcome this problem, is by creating your own proxy in the back-end, so that your proxy will point to the services in other domains, because in the back-end not exists the same origin policy restriction. But if you can't do that in back-end, then pay attention to the following tips.

克服这个问题的最佳方法是在后端创建您自己的代理,这样您的代理将指向其他域中的服务,因为在后端不存在相同的起源策略限制。但是如果在后端无法做到这一点,那么请注意以下技巧。


Warning!

Using third-party proxies is not a secure practice, because they can keep track of your data, so it can be used with public information, but never with private data.

使用第三方代理不是一种安全的做法,因为它们可以跟踪您的数据,因此可以将其用于公共信息,但不能用于私有数据。


The code examples shown below use jQuery.get() and jQuery.getJSON(), both are shorthand methods of jQuery.ajax()


CORS Anywhere

CORS Anywhere is a node.js proxy which adds CORS headers to the proxied request.
To use the API, just prefix the URL with the API URL. (Supports https: see github repository)

CORS任何地方都是一个节点。js代理,向被代理的请求添加CORS头。要使用API,只需在URL前面加上API URL的前缀。(支持https:参见github存储库)

If you want to automatically enable cross-domain requests when needed, use the following snippet:

如果您希望在需要时自动启用跨域请求,请使用以下代码片段:

$.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);
});


Whatever Origin

Whatever Origin is a cross domain jsonp access. This is an open source alternative to anyorigin.com.

无论来源是跨域jsonp访问。这是对anyorigin.com的开源替代方案。

To fetch the data from google.com, you can use this snippet:

要从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 Proxy

CORS Proxy is a simple node.js proxy to enable CORS request for any website. It allows javascript code on your site to access resources on other domains that would normally be blocked due to the same-origin policy.

CORS代理是一个简单的节点。js代理,为任何网站启用CORS请求。它允许站点上的javascript代码访问其他域上的资源,这些域通常由于同源策略而被阻塞。

How does it work? CORS Proxy takes advantage of Cross-Origin Resource Sharing, which is a feature that was added along with HTML 5. Servers can specify that they want browsers to allow other websites to request resources they host. CORS Proxy is simply an HTTP Proxy that adds a header to responses saying "anyone can request this".

它是如何工作的呢?CORS代理利用了跨源资源共享,这是与HTML 5一起添加的特性。服务器可以指定它们希望浏览器允许其他网站请求它们托管的资源。CORS代理是一个简单的HTTP代理,它向响应添加一个头,表示“任何人都可以请求它”。

This is another way to achieve the goal (see www.corsproxy.com). All you have to do is strip http:// and www. from the URL being proxied, and prepend the URL with www.corsproxy.com/

这是实现目标的另一种方式(参见www.corsproxy.com)。你所要做的就是去掉http://和www。从被代理的URL中,并以www.corsproxy.com/来prepend URL。

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


CORS proxy browser

Recently I found this one, it involves various security oriented Cross Origin Remote Sharing utilities. But it is a black-box with Flash as backend.

最近我发现了这个,它涉及到各种安全导向的跨源远程共享实用程序。但它是一个带有Flash的黑盒。

You can see it in action here: CORS proxy browser
Get the source code on GitHub: koto/cors-proxy-browser

您可以在这里看到它的作用:CORS代理浏览器在GitHub: koto/ CORS -proxy-browser上获取源代码

#2


19  

You can use Ajax-cross-origin a jQuery plugin. With this plugin you use jQuery.ajax() cross domain. It uses Google services to achieve this:

您可以使用Ajax-cross-origin - jQuery插件。使用这个插件,您可以使用jQuery.ajax()跨域。它使用谷歌服务来实现这一点:

The AJAX Cross Origin plugin use Google Apps Script as a proxy jSON getter where jSONP is not implemented. When you set the crossOrigin option to true, the plugin replace the original url with the Google Apps Script address and send it as encoded url parameter. The Google Apps Script use Google Servers resources to get the remote data, and return it back to the client as JSONP.

AJAX Cross - Origin插件使用谷歌Apps Script作为代理jSON getter, jSONP没有实现。当您将crossOrigin选项设置为true时,插件将用谷歌应用程序脚本地址替换原始url并将其作为编码url参数发送。谷歌应用程序脚本使用谷歌服务器资源获取远程数据,并将其作为JSONP返回给客户机。

It is very simple to use:

使用起来非常简单:

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

You can read more here: http://www.ajax-cross-origin.com/

你可以在这里阅读更多:http://www.ajax-cross-origin.com/

#3


11  

If the external site doesn't support JSONP or CORS, your only option is to use a proxy.

如果外部站点不支持JSONP或CORS,那么您唯一的选择就是使用代理。

Build a script on your server that requests that content, then use jQuery ajax to hit the script on your server.

在您的服务器上构建一个请求该内容的脚本,然后使用jQuery ajax攻击服务器上的脚本。

#4


0  

I'm posting this in case someone faces the same problem I am facing right now. I've got a Zebra thermal printer, equipped with the ZebraNet print server, which offers a HTML-based user interface for editing multiple settings, seeing the printer's current status, etc. I need to get the status of the printer, which is displayed in one of those html pages, offered by the ZebraNet server and, for example, alert() a message to the user in the browser. This means that I have to get that html page in Javascript first. Although the printer is within the LAN of the user's PC, that Same Origin Policy is still staying firmly in my way. I tried JSONP, but the server returns html and I haven't found a way to modify its functionality (if I could, I would have already set the magic header Access-control-allow-origin: *). So I decided to write a small console app in C#. It has to be run as Admin to work properly, otherwise it trolls :D an exception. Here is some code:

我把这贴出来,以防有人遇到我现在面临的问题。我有斑马热打印机,配备了ZebraNet打印服务器,它提供了一个基于html的用户界面编辑多个设置,看到打印机的当前状态,等等。我需要打印机的状态,这是显示在一个html页面,ZebraNet服务器提供的,例如,警报()消息发送到用户的浏览器。这意味着我必须首先在Javascript中获得html页面。虽然打印机是在用户个人电脑的局域网内,但同样的原产地政策仍在我的道路上。我尝试了JSONP,但是服务器返回html,我还没有找到修改它的功能的方法(如果可以的话,我应该已经设置了魔法头的访问控制允许的来源:*)。所以我决定用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();

All the user needs to do is run that console app as Admin. I know it is way too ... frustrating and complicated, but it is sort of a workaround to the Domain Policy problem in case you cannot modify the server in any way.

用户需要做的就是以管理员的身份运行控制台应用程序。我知道这也太……令人沮丧和复杂,但这是域策略问题的解决方案,以防您无法以任何方式修改服务器。

edit: from js I make a simple ajax call:

编辑:从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);
                }
            });

The html of the requested page is returned and stored in the data variable.

返回所请求页面的html并将其存储在数据变量中。

#5


0  

To get the data form external site by passing using a local proxy as suggested by jherax you can create a php page that fetches the content for you from respective external url and than send a get request to that php page.

要通过使用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);
}

as a php proxy you can use https://github.com/cowboy/php-simple-proxy

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

#6


0  

Just put this in the header of your PHP Page and it ill work without API:

把这个放到PHP页面的头,没有API就不行:

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

or

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

or

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

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

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

#7


-2  

You need CORS proxy which proxies your request from your browser to requested service with appropriate CORS headers. List of such services are in code snippet below. You can also run provided code snippet to see ping to such services from your location.

您需要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>

#8


-7  

Figured it out. Used this instead.

算出来。用这个来代替。

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

#1


197  

jQuery Ajax Notes

  • Due to browser security restrictions, most Ajax requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
  • 由于浏览器安全限制,大多数Ajax请求都遵循相同的源策略;请求不能成功地从不同的域、子域、端口或协议中检索数据。
  • Script and JSONP requests are not subject to the same origin policy restrictions.
  • 脚本和JSONP请求不受相同的源策略限制。

There are some ways to overcome the cross-domain barrier:

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

There are some plugins that help with cross-domain requests:

有一些插件可以帮助跨域请求:

Heads up!

小心!

The best way to overcome this problem, is by creating your own proxy in the back-end, so that your proxy will point to the services in other domains, because in the back-end not exists the same origin policy restriction. But if you can't do that in back-end, then pay attention to the following tips.

克服这个问题的最佳方法是在后端创建您自己的代理,这样您的代理将指向其他域中的服务,因为在后端不存在相同的起源策略限制。但是如果在后端无法做到这一点,那么请注意以下技巧。


Warning!

Using third-party proxies is not a secure practice, because they can keep track of your data, so it can be used with public information, but never with private data.

使用第三方代理不是一种安全的做法,因为它们可以跟踪您的数据,因此可以将其用于公共信息,但不能用于私有数据。


The code examples shown below use jQuery.get() and jQuery.getJSON(), both are shorthand methods of jQuery.ajax()


CORS Anywhere

CORS Anywhere is a node.js proxy which adds CORS headers to the proxied request.
To use the API, just prefix the URL with the API URL. (Supports https: see github repository)

CORS任何地方都是一个节点。js代理,向被代理的请求添加CORS头。要使用API,只需在URL前面加上API URL的前缀。(支持https:参见github存储库)

If you want to automatically enable cross-domain requests when needed, use the following snippet:

如果您希望在需要时自动启用跨域请求,请使用以下代码片段:

$.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);
});


Whatever Origin

Whatever Origin is a cross domain jsonp access. This is an open source alternative to anyorigin.com.

无论来源是跨域jsonp访问。这是对anyorigin.com的开源替代方案。

To fetch the data from google.com, you can use this snippet:

要从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 Proxy

CORS Proxy is a simple node.js proxy to enable CORS request for any website. It allows javascript code on your site to access resources on other domains that would normally be blocked due to the same-origin policy.

CORS代理是一个简单的节点。js代理,为任何网站启用CORS请求。它允许站点上的javascript代码访问其他域上的资源,这些域通常由于同源策略而被阻塞。

How does it work? CORS Proxy takes advantage of Cross-Origin Resource Sharing, which is a feature that was added along with HTML 5. Servers can specify that they want browsers to allow other websites to request resources they host. CORS Proxy is simply an HTTP Proxy that adds a header to responses saying "anyone can request this".

它是如何工作的呢?CORS代理利用了跨源资源共享,这是与HTML 5一起添加的特性。服务器可以指定它们希望浏览器允许其他网站请求它们托管的资源。CORS代理是一个简单的HTTP代理,它向响应添加一个头,表示“任何人都可以请求它”。

This is another way to achieve the goal (see www.corsproxy.com). All you have to do is strip http:// and www. from the URL being proxied, and prepend the URL with www.corsproxy.com/

这是实现目标的另一种方式(参见www.corsproxy.com)。你所要做的就是去掉http://和www。从被代理的URL中,并以www.corsproxy.com/来prepend URL。

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


CORS proxy browser

Recently I found this one, it involves various security oriented Cross Origin Remote Sharing utilities. But it is a black-box with Flash as backend.

最近我发现了这个,它涉及到各种安全导向的跨源远程共享实用程序。但它是一个带有Flash的黑盒。

You can see it in action here: CORS proxy browser
Get the source code on GitHub: koto/cors-proxy-browser

您可以在这里看到它的作用:CORS代理浏览器在GitHub: koto/ CORS -proxy-browser上获取源代码

#2


19  

You can use Ajax-cross-origin a jQuery plugin. With this plugin you use jQuery.ajax() cross domain. It uses Google services to achieve this:

您可以使用Ajax-cross-origin - jQuery插件。使用这个插件,您可以使用jQuery.ajax()跨域。它使用谷歌服务来实现这一点:

The AJAX Cross Origin plugin use Google Apps Script as a proxy jSON getter where jSONP is not implemented. When you set the crossOrigin option to true, the plugin replace the original url with the Google Apps Script address and send it as encoded url parameter. The Google Apps Script use Google Servers resources to get the remote data, and return it back to the client as JSONP.

AJAX Cross - Origin插件使用谷歌Apps Script作为代理jSON getter, jSONP没有实现。当您将crossOrigin选项设置为true时,插件将用谷歌应用程序脚本地址替换原始url并将其作为编码url参数发送。谷歌应用程序脚本使用谷歌服务器资源获取远程数据,并将其作为JSONP返回给客户机。

It is very simple to use:

使用起来非常简单:

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

You can read more here: http://www.ajax-cross-origin.com/

你可以在这里阅读更多:http://www.ajax-cross-origin.com/

#3


11  

If the external site doesn't support JSONP or CORS, your only option is to use a proxy.

如果外部站点不支持JSONP或CORS,那么您唯一的选择就是使用代理。

Build a script on your server that requests that content, then use jQuery ajax to hit the script on your server.

在您的服务器上构建一个请求该内容的脚本,然后使用jQuery ajax攻击服务器上的脚本。

#4


0  

I'm posting this in case someone faces the same problem I am facing right now. I've got a Zebra thermal printer, equipped with the ZebraNet print server, which offers a HTML-based user interface for editing multiple settings, seeing the printer's current status, etc. I need to get the status of the printer, which is displayed in one of those html pages, offered by the ZebraNet server and, for example, alert() a message to the user in the browser. This means that I have to get that html page in Javascript first. Although the printer is within the LAN of the user's PC, that Same Origin Policy is still staying firmly in my way. I tried JSONP, but the server returns html and I haven't found a way to modify its functionality (if I could, I would have already set the magic header Access-control-allow-origin: *). So I decided to write a small console app in C#. It has to be run as Admin to work properly, otherwise it trolls :D an exception. Here is some code:

我把这贴出来,以防有人遇到我现在面临的问题。我有斑马热打印机,配备了ZebraNet打印服务器,它提供了一个基于html的用户界面编辑多个设置,看到打印机的当前状态,等等。我需要打印机的状态,这是显示在一个html页面,ZebraNet服务器提供的,例如,警报()消息发送到用户的浏览器。这意味着我必须首先在Javascript中获得html页面。虽然打印机是在用户个人电脑的局域网内,但同样的原产地政策仍在我的道路上。我尝试了JSONP,但是服务器返回html,我还没有找到修改它的功能的方法(如果可以的话,我应该已经设置了魔法头的访问控制允许的来源:*)。所以我决定用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();

All the user needs to do is run that console app as Admin. I know it is way too ... frustrating and complicated, but it is sort of a workaround to the Domain Policy problem in case you cannot modify the server in any way.

用户需要做的就是以管理员的身份运行控制台应用程序。我知道这也太……令人沮丧和复杂,但这是域策略问题的解决方案,以防您无法以任何方式修改服务器。

edit: from js I make a simple ajax call:

编辑:从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);
                }
            });

The html of the requested page is returned and stored in the data variable.

返回所请求页面的html并将其存储在数据变量中。

#5


0  

To get the data form external site by passing using a local proxy as suggested by jherax you can create a php page that fetches the content for you from respective external url and than send a get request to that php page.

要通过使用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);
}

as a php proxy you can use https://github.com/cowboy/php-simple-proxy

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

#6


0  

Just put this in the header of your PHP Page and it ill work without API:

把这个放到PHP页面的头,没有API就不行:

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

or

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

or

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

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

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

#7


-2  

You need CORS proxy which proxies your request from your browser to requested service with appropriate CORS headers. List of such services are in code snippet below. You can also run provided code snippet to see ping to such services from your location.

您需要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>

#8


-7  

Figured it out. Used this instead.

算出来。用这个来代替。

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