jquery 使用 AJAX 加载跨域终结点

btxsgosb  于 2022-12-03  发布在  jQuery
关注(0)|答案(9)|浏览(141)

我尝试使用 AJAX 加载一个跨域HTML页面,但是除非dataType是“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回复中说“unexpected〈”。

iih3973s

iih3973s1#

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.
  • Script and JSONP requests are not subject to the same origin policy restrictions.

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

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

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.

CORS Anywhere

2021 Update

Public demo server (cors-anywhere.herokuapp.com) will be very limited by January 2021, 31st
The demo server of CORS Anywhere (cors-anywhere.herokuapp.com) is meant to be a demo of this project. But abuse has become so common that the platform where the demo is hosted (Heroku) has asked me to shut down the server, despite efforts to counter the abuse. Downtime becomes increasingly frequent due to abuse and its popularity.
To counter this, I will make the following changes:

  1. The rate limit will decrease from 200 per hour to 50 per hour.
  2. By January 31st, 2021, cors-anywhere.herokuapp.com will stop serving as an open proxy.
  3. From February 1st. 2021, cors-anywhere.herokuapp.com will only serve requests after the visitor has completed a challenge: The user (developer) must visit a page at cors-anywhere.herokuapp.com to temporarily unlock the demo for their browser. This allows developers to try out the functionality, to help with deciding on self-hosting or looking for alternatives.
    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 )
    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 .
To fetch the data from google.com, you can use this snippet:

// 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.

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".
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/

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

The http://www.corsproxy.com/ domain now appears to be an unsafe/suspicious site. NOT RECOMMENDED TO USE.

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.
You can see it in action here: CORS proxy browser
Get the source code on GitHub: koto/cors-proxy-browser

ckocjqey

ckocjqey2#

你可以使用Ajax-cross-origin一个jQuery插件。通过这个插件你可以使用jQuery.ajax()跨域。它使用Google服务来实现这一点:
AJAX Cross Origin插件使用Google Apps Script作为代理JSON getter,其中未实现jSONP。当您将crossOrigin选项设置为true时,插件会将原始url替换为Google Apps Script地址,并将其作为编码url参数发送。Google Apps Script使用Google服务器资源获取远程数据,并将其作为JSONP返回给客户端。
使用起来非常简单:

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

您可以在此处阅读更多信息:http://www.ajax-cross-origin.com/

ycggw6v2

ycggw6v23#

如果外部站点不支持JSONP或CORS,您唯一的选择就是使用代理。
在您的服务器上构建一个请求该内容的脚本,然后使用 AJAX 在您的服务器上点击该脚本。

2mbi3lxu

2mbi3lxu4#

只要把这个放在你的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");
}
jm81lzqq

jm81lzqq5#

我发布这篇文章是为了防止有人遇到我现在面临的同样问题。我有一台Zebra热敏打印机,配备了ZebraNet打印服务器,它提供了一个基于HTML的用户界面,用于编辑多个设置,查看打印机的当前状态等。我需要获得打印机的状态,它显示在ZebraNet服务器提供的其中一个html页面中,例如,警戒()在浏览器中向用户发送一条消息。这意味着我必须首先用Javascript获取html页面。尽管打印机位于用户PC的LAN内,但Same Origin Policy仍然牢牢地挡在我的路上。我尝试了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();

所有的用户需要做的是运行控制台应用程序作为管理员。我知道这是太...令人沮丧和复杂的方式,但它是一种解决域策略问题的方法,以防您无法以任何方式修改服务器。
edit:from 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变量中。

b1zrtrql

b1zrtrql6#

要像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

2ledvvac

2ledvvac7#

您的URL现在不工作了,但是您的代码可以使用以下工作解决方案进行更新:
第一个

aij0ehis

aij0ehis8#

您需要CORS代理,它将您的请求从浏览器代理到具有相应CORS headers的请求服务。此类服务的列表在下面的代码段中。您还可以运行提供的代码段,以查看从您的位置对此类服务的ping。
第一个

wqsoz72f

wqsoz72f9#

我想出来了。用这个代替。

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

相关问题