External Connection JSON WebService

3

I have a webservice in PHP feeding data from a array via JSON , to read in an HTML file.

When I run the application having $.get with a local file it works, but when I change the path to read the same file on my server, it does not connect.

I noticed in the console that there is an impediment to connections via localhost.

Considering that this application will be run from the base PhoneGap , what would be the best alternative to address this problem?

    
asked by anonymous 02.07.2014 / 02:35

4 answers

1

It's only localhost running, right? then the problem might be because it is not releasing the cross-domain, it must allow external access in the header:

<php>
header('Access-Control-Allow-Origin: *');

link

    
07.07.2014 / 13:09
1

This problem is very common in webservices I suggest you study about CORS link .

This is a problem that has to be solved both on the server and in your client application being it a JS or another client.

To solve this on the server you can do as follows, just call this php function in your input file

  function cors() {

// permite para qualquer origem
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache por 1 dia
}

// Essa parte cuida do preflight request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {


    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    header("Access-Control-Allow-Headers: Accept, Content-Type");

    exit(0);
}

echo "Você está com CORS!";
}

Remembering that it is not legal to access global variables like $ _SERVER directly strongly recommend some php package that does this, if possible a framework or mini framework for this service link already help.

To resolve this from the client side, just activate CORS in the jquery or http of the angle in which you prefer

  $.ajax({
        url: "http://example.com/minha/acao/",
        type: "POST",
        crossDomain: true,
        data: {conteudopost: "algumacoisa"},
        dataType: "json",
        success: function (response) {
          //sucesso
        },
        error: function (xhr, status) {
            //erro
        }
    });

Basically this is any question leave a comment ai, vlw

    
06.08.2014 / 14:42
0

I use the? callback =? to be able to access json webservices outside the local domain. Example below.

<script type="text/javascript>
  $(document).ready(function(){
     $.getJSON("http://dominioexterno.com/caminho-do-get/?callback=?", function(exemplo){

        //o que voce quer fazer.

     });
  });  
</script>

There is also the JSONP option, to take a look at this link here: Jquery Cross-Domain ajax call using JSONP

    
02.07.2014 / 16:25
0

I ended up migrating to Angular.js and adopting the more structured CORS to serve my application.

    
05.09.2014 / 23:30