No 'Access-Control-Allow-Origin' header using php

0

I'm trying to make a simple request via localhost to an external server, but to no avail. Can anyone help me?

$(function(){
        jQuery.support.cors = true;
        $.ajax({
            type: 'get',
            crossDomain: true,
            url: 'http://meusiteaqui.com',
            success:function(e){
                //window.location=e;
                alert(e)
            }
        })

    });
    
asked by anonymous 13.02.2016 / 04:59

1 answer

1

This is because meusiteaqui.com is not authorizing, there are two solutions:

1. Authorize via Header:

You need to add this:

<?
header("Access-Control-Allow-Origin: *");

//...
?>

On the page in question, to allow the connection of any other site, including localhost . Some browsers may continue to prevent this for security reasons.

You can also do this in htaccess, for example :

<FilesMatch "\.(php|html|htm)$">
    <IfModule mod_headers>
        Header set Access-Control-Allow-Origin "*"
    </IfModule>
</FilesMatch>

2. Use JSONP:

Modify your PHP for something similar:

$seusDados = array('id' => 1);
// Exemplo

$seuJSON = json_encode($seusDados);

if(isset($_GET['jsonp'])){
  echo $_GET['jsonp'] . '(' . $seuJSON . ')';
}else{
  echo $seuJSON;
}

You can use something similar to:

<script>

MinhaResposta(MeuJSONP){
   alert(MeuJSONP.id)
}

</script>
<script type="text/javascript" src="http://meusiteaqui.com?jsonp=MinhaResposta"></script>

IfyouwanttoknowmoreaboutJSONP click here .

    
13.02.2016 / 05:07