Ajax cross domain

7

Hello some time ago I asked this question:

Paste content of another page by javascript or jquery

The colleague @SneepSNinjA made the following algorithm that worked.

$(document).ready(function(){
	$("button").click(function(){
		site = $("#site").val();
		$.ajax({
			url: site,
			type: 'GET',
			success: function(res) {
				var headline = $(res.responseText).text();
				$("#conteudo").html(headline);
			}
		});
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><head><!--ScriptsJavascript--><scripttype="text/javascript" src="http://projetos.lucaspeperaio.com.br/ajax-cross-domain/jquery.xdomainajax.js"></script><title>jQueryeAjaxCrossDomain</title></head><body><inputtype="text" id="site" value="http://" />
<button id="acessar">Clique para obter o conteúdo deste site</button>
<div id="conteudo" style="background:#EEF0A6"></div>
</body>
</html>

However, there is a problem. This code takes cross domain content. But it does not work for all protocol types.

If you have an http site it works correctly, however if you have an https site it will not work. (If it is in an http protocol it will get http content but if it is in an https it gives an error.)

I want to implement this function in the site: link

and it gives the following error:

Example with https protocol:

Ichangedtheprotocolanditworked,butithastoworkonbothprotocols(Wellit'sgoingtobeanAPI).

Examplewithhttp:protocol

I came to the conclusion with this error that the protocol should be http to work on the site. But since I am making an API the script does not have to just call the two protocols, it also has to work in both protocols.

Can anyone help me?

There are some similar issues, but you do not just need to get cross domain content, it needs to work on both types of protocols. It has to work for both http and https.

Load and read XML via AJAX Cross-Domain

Requisition Ajax cross-domain with pure Javascript (without APIs)

This is why it would not be feasible to change the protocol to http.

I was thinking of maybe using an if, if it is http it uses one domain to cross if it is https it uses another.

But perhaps you have a more practical solution.

Help me out ~ ~

    
asked by anonymous 17.07.2015 / 19:21

3 answers

9

Instead of specifying the protocol in the src property:

<script 
        type="text/javascript" 
        src="http://projetos.lucaspeperaio.com.br/ajax-cross-domain/jquery.xdomainajax.js"></script>

Omitit.

<scripttype="text/javascript" 
        src="//projetos.lucaspeperaio.com.br/ajax-cross-domain/jquery.xdomainajax.js"
></script>

The name of this practice is Protocol-Relative URL , specified in < a href="https://tools.ietf.org/html/rfc1808"> RFC 1808 .

This will make the browser load the resource using the same protocol as the page that calls it.

Keep in mind, however, that in the current version of Internet Explorer a PRURL will cause the browser to always try to load both the HTTP version and the HTTPS version, thus causing two requests.

    
20.07.2015 / 21:25
6

If the site in question has access both by http and https you simply remove the protocol from the request that the browser will use the current protocol. This technique is widely used to load libraries through a CDN.

For example, http://exemplo.com/usuarios (or https://exemplo.com/usuarios ) would be //exemplo.com/usuarios and the browser will automatically fetch through the current protocol ( http on localhost and sites that use http and https on server).

    
20.07.2015 / 21:25
3

Edited

I'm going to pass an example already running with the site in question, and I'll pass the https:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><head><!--ScriptsJavascript--><title>jQueryeAjaxCrossDomain</title></head><body><inputtype="text" id="site" value="https://ebookstore.xtechcommerce.com/acessorios" size="100" />
<button id="acessar">Clique para obter o conteúdo deste site</button>
<div id="conteudo" style="background:#EEF0A6"></div>
<script>
    /**
 * jQuery.ajax mid - CROSS DOMAIN AJAX 
 * ---
 * @author James Padolsey (http://james.padolsey.com)
 * @version 0.11
 * @updated 12-JAN-10
 * ---
 * Note: Read the README!
 * ---
 * @info http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
 */

jQuery.ajax = (function(_ajax){
    
    var protocol = location.protocol,
        hostname = location.hostname,
        exRegex = RegExp(protocol + '//' + hostname),
        YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
        query = 'select * from html where url="{URL}" and xpath="*"';
    
    function isExternal(url) {
        return !exRegex.test(url) && /:\/\//.test(url);
    }
    
    return function(o) {
        
        var url = o.url;
        
        if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
            
            // Manipulate options so that JSONP-x request is made to YQL
            
            o.url = YQL;
            o.dataType = 'json';
            
            o.data = {
                q: query.replace(
                    '{URL}',
                    url + (o.data ?
                        (/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
                    : '')
                ),
                format: 'xml'
            };
            
            // Since it's a JSONP request
            // complete === success
            if (!o.success && o.complete) {
                o.success = o.complete;
                delete o.complete;
            }
            
            o.success = (function(_success){
                return function(data) {
                    
                    if (_success) {
                        // Fake XHR callback.
                        _success.call(this, {
                            responseText: data.results[0]
                                // YQL screws with <script>s
                                // Get rid of them
                                .replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
                        }, 'success');
                    }
                    
                };
            })(o.success);
            
        }
        
        return _ajax.apply(this, arguments);
        
    };
    
})(jQuery.ajax);
    $(document).ready(function(){
	$("button").click(function(){
		site = $("#site").val();
		$.ajax({
			url: site,
			type: 'GET',
			success: function(res) {
				//var headline = $(res.responseText).text();                                
				//$("#conteudo").html(headline);
                                $('#conteudo').html(res.responseText);
			}
		});
	});
        $("#acessar").click();
});
</script>
</body>
</html>

It ran normally, the only errors I encountered were ref. the images, so I still do not understand where that error happens . I ran the localhost where my apache is link HTTPS, then I ran it here in the SOPT where it is https , and I tested the site with the link you passed (https) and it worked.

OBS: The merged content loading error occurs because your https service needs to receive the jquery.xdomainajax.js file at https, as you are linking it to http he gives this error, try to use the example I passed now where I do not do that mixed loading that will run, and / or write the plugin part in a separate file on your https server and call it or write the whole plugin as I did too resolve.

    
20.07.2015 / 16:22