How do I return the weather forecast through the previsaodotempo.org API?

2

I'm trying to return a weather forecast query through the link API but I'm not getting any success. Where am I going wrong?

$.getJSON('http://www.previsaodotempo.org/api.php?city=rio+de+janeiro', function(data){
    $('.temperatura').text( "Temperatura:" );
}).done(function() {
    $('.sucesso').text( "second success" );
})
.fail(function() {
    $('.sucesso').text( "error" );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='sucesso'></span>
<span class='temperatura'></span>
    
asked by anonymous 20.02.2015 / 21:52

1 answer

5

The problem is that you are attempting to cross-domain a request via ajax, which is not allowed due to Policy from the same source (unless the target domain supports CORS ).

JSONP would be an alternative, but the previsaodotempo.org API does not seem to support this.

I do not know if it is feasible for you, but another alternative is to create a file on your local server to serve as a proxy. This file would request the API and return JSON to you. This way your so-called ajax would become local.

If your server supports PHP, you can use the following:

PHP (api.php):

<?php
header('Content-Type: text/plain; charset=utf-8;'); 
exit(file_get_contents("http://www.previsaodotempo.org/api.php?city=" . $_GET['city']));

Javascript:

$.getJSON('http://[endereço-do-seu-site]/api.php?city=rio+de+janeiro', function(data){
    $('.temperatura').text( "Temperatura:" );
}).done(function() {
    $('.sucesso').text( "second success" );
})
.fail(function() {
    $('.sucesso').text( "error" );
});

Your Javascript will get exactly what the API returns.

    
21.02.2015 / 01:03