Ajax cross Domain

Asked

Viewed 1,766 times

8

Hello a while ago I asked this question:

Grab content from another page by javascript or jquery

Fellow @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>
<!-- Scripts Javascript -->
<script type="text/javascript" src="http://projetos.lucaspeperaio.com.br/ajax-cross-domain/jquery.xdomainajax.js"></script>
<title>jQuery e Ajax Cross Domain</title>
</head>

<body>
<input type="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 content from Omain. But it does not work for all types of protocol.

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

I’m willing to implement this function on the site: https://ebookstore.xtechcommerce.com/acessorios

and he makes the following mistake:

Example with https protocol:

Exemplo do erro cross domain

I switched the protocol and it worked, but it has to work on both protocols (because it will be an API).


Example with http protocol:

inserir a descrição da imagem aqui

I came to the conclusion with this error that the protocol should be http to work on the site. But since I’m making an API the script doesn’t have to only call the two protocols, it also has to work on the two protocols.

Can someone help me?

There are some similar questions, but you don’t just need to take cross-Omain content, it needs to work in both types of protocols. It has to work for both http and https.

Load and read XML via AJAX Cross-Domain

Ajax cross-Omain request with pure Javascript (no Apis)

For this it would not be feasible to change the protocol to http.

I was thinking maybe use an if, if it’s http it uses a domain to cross if it’s https it uses another.

But I may have a more practical solution.

Help me ^~

  • I recently solved a problem similar to a Jason give in a domain without headers, as I had access to the api that listed the json I just did a php q copy the content of the url of that json and save in a json inside my Server, and so I could read everything without problem. I did a Cron task on the Server that ran the php copy script every 1 hour keeping my json up to date. Sometimes it’s an output.

  • Congratulations to the others who also arrived at the same solution, but I decided first :P

  • I will check the answers one by one and reward who gave the best solution. Thank you

  • already checked if there is an error with output: //projects.lucaspeperaio.com.br/ajax-cross-Domain/jquery.xdomainajax.js

3 answers

10


Instead of specifying the protocol in the property src:

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

Leave it out.

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

The name of this practice is Protocol-Relative URL (protocol URL), specified in 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 make the browser always try to load both the HTTP version and the HTTPS version, thus causing two requests.

  • +1, your answer summarizes what I answered =)

7

If the site in question has access both by http how much for https just 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, the url http://exemplo.com/usuarios (or https://exemplo.com/usuarios) would be //exemplo.com/usuarios and the browser will automatically search through the current protocol (http on localhost and sites that use http and https on the server).

  • +1, your answer is essentially correct. =)

4

Edited

I will pass an example already running with the site in question, and I will pass the https:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<!-- Scripts Javascript -->

<title>jQuery e Ajax Cross Domain</title>
</head>

<body>
    <input type="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>

Rotated normally, the only errors I found were ref. the images, then I still don’t understand where the mistake happens. I rode localhost where my apache is http HTTPS, then I circled here at SOPT where it’s https, and tested the site with the link you passed (https) and worked.

OBS: The mixed content loading error occurs because your https service needs to receive the jquery.xdomainajax.js file on https, as you are linking it to http from that error, try using the example I just passed where I don’t do this merged upload that will run, and/or save the plugin part into a separate file on your https server and call it or write the entire plugin as I did that also resolves.

  • It is simple, depending on the protocol of the site it gives error, if the protocol is http: it does not give error, if it is https it gives error. We can test this by simply entering the cart site, there the protocol is https so it will give error. You could not see the error because the website protocol is http, if you enter the cart it will flip https and will show the error.

  • What are you trying to do? In case the protocol I say is the one on the server. You tested it on an https server?

  • I think you do not understand the question, the problem is not the code but the protocol. That is: The protocol used on the hosted site. Stack Overflow uses http protocol, so the code will work. Now if you use this code in an https protocol it will fail.

  • @Felipejorge was able to simulate the error of loading mixed, I edited again the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.