How to get JSON data an external website?

1

I want to get the value of a JSON that I send from another external web example:

I'm sending this from the other website

text.php

 <?php
   echo json_encode(array("texto"=>"ejemplo"));
?>

{"texto":"ejemplo"}

And now I want to retrieve the text value in my other web, how would I do it?

Link: link

    
asked by Jhosselin Giménez 15.03.2017 в 03:27
source

3 answers

2

Call it by ajax

$.ajax ({
  url : 'text.php',
  dataType: 'json'
}).then ((resultado) => {
  console(resultado);
});

The result contains the obtained text.php

    
answered by 15.03.2017 в 03:53
2

As they already told you, you can do it by AJAX; however, you will run into a security restriction due to being cross domains and in the absence of CORS configuration on said server.

$.ajax({
  url: 'http://aimbotdb.pe.hu/test.php',
  dataType: 'json'
}).done(data => console.log(data));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you make that request and look at the browser console, you will see the following message:

  

XMLHttpRequest can not load http://aimbotdb.pe.hu/test.php . No ' Access-Control-Allow-Origin ' header is present in the requested resource. Origin 'null' is therefore not allowed access .

The above message means that the server has not enabled CORS . CORS is simply adding the header Access-Control-Allow-Origin in the server response; In this way, you "allow" other domains to access that resource. In the case of XMLHttpRequest (interface for AJAX requests), this interface follows the policy of the same origin .

You must make the request in the backend

To avoid this restriction, you must obtain the data in the backend. An example in PHP is the following:

$json = json_encode(file_get_contents('http://aimbotdb.pe.hu/test.php'));
    
answered by 15.03.2017 в 13:54
0

For security reasons, the default requests in jQuery when using AJAX, do not allow it to be to other domains. You can occupy JSONP. I recommend the following article: link or also link

Documentation: link

    
answered by 15.03.2017 в 22:30