Javascript 使用AJAX加载跨域端点

Javascript 使用AJAX加载跨域端点,javascript,jquery,ajax,cross-domain,Javascript,Jquery,Ajax,Cross Domain,我试图使用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=%

我试图使用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或CORS,那么您唯一的选择就是使用代理

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

jQuery ajax注释
  • 由于浏览器的安全性限制,大多数Ajax请求都受到限制;该请求无法成功地从不同的域、子域、端口或协议检索数据
  • 脚本和JSONP请求不受同源策略限制
有一些方法可以克服跨域障碍:

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

抬起头来!

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


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


下面显示的代码示例使用了,两者都是的速记方法


任何地方都可以 2021年更新

CORS Anywhere的演示服务器(CORS Anywhere.herokuapp.com)本应作为该项目的演示。但滥用已变得如此普遍,以至于演示所在的平台(Heroku)要求我关闭服务器,尽管已采取措施阻止滥用。由于滥用及其流行,宕机变得越来越频繁

为了解决这个问题,我将进行以下更改:

  • 收费上限将从每小时200英镑降至每小时50英镑
  • 到2021年1月31日,cors-anywhere.herokuapp.com将不再担任公开代理
  • 从2021年2月1日起,cors-anywhere.herokuapp.com将仅在访问者完成挑战后提供请求:用户(开发人员)必须访问cors-anywhere.herokuapp.com上的页面,以临时解锁其浏览器的演示。这允许开发人员尝试该功能,以帮助决定是否自行托管或寻找替代方案

  • CORS Anywhere是一个node.js代理,它将CORS头添加到代理请求中。
    要使用API,只需在URL前面加上API URL。(支持https
    :请参阅)

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

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

    无论起源如何 是一种跨域jsonp访问。这是一种开源的替代方法

    要从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 Proxy利用了跨源资源共享的优势,这是与HTML 5一起添加的一项功能。服务器可以指定它们希望浏览器允许其他网站请求它们托管的资源。CORS Proxy只是一个HTTP代理,它在响应中添加了一个标题“任何人都可以请求”

    这是实现目标的另一种方法(请参阅)。您所要做的就是从代理的URL中剥离http://www.,并在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为后端的黑匣子

    您可以在此处看到它的作用:

    在GitHub上获取源代码:

    您可以使用Ajax跨源jQuery插件。 使用此插件,您可以跨域使用
    jQuery.ajax()

    AJAX跨源插件使用GoogleApps脚本作为jSON代理 未实现jSONP的getter。设置交叉源时 选项为true时,插件将用Google 应用程序脚本地址,并将其作为编码url参数发送 应用程序脚本使用Google服务器资源获取远程数据,以及 将其作为JSONP返回给客户机

    使用起来非常简单:

        $.ajax({
            crossOrigin: true,
            url: url,
            success: function(data) {
                console.log(data);
            }
        });
    
    您可以在此处阅读更多内容:

    把它弄明白了。 用这个代替

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

    我发布这篇文章是为了防止有人面临与我现在面临的问题相同的问题。我有一台Zebra热敏打印机,配备了ZebraNet打印服务器,它提供了一个基于HTML的用户界面,用于编辑多个设置、查看打印机的当前状态等。我需要获取打印机的状态,它显示在其中一个ht中ZebraNet服务器提供的ml页面,例如alert()在浏览器中发送给用户的消息。这意味着我必须先获取Javascript格式的html页面。虽然打印机位于用户PC的LAN内,但这仍然是我的障碍。我尝试了JSONP,但服务器返回html,我还没有找到修改其功能的方法(如果我
    // 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();
    
    $.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);
                    }
                });
    
    var req = new XMLHttpRequest();
    req.open('GET', 'http://localhost/get_url_content.php',false);
    if(req.status == 200) {
       alert(req.responseText);
    }
    
    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");
    }