How to return the weather forecast via the prediction API dotempo.org?

Asked

Viewed 2,775 times

2

I’m trying to return a weather forecast query via the http://www.previsaodotempo.org but I’m not succeeding. Where I’m 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>

  • Please complete your question, this very weak, bearing the rest of the code...

  • @Jeiferson what’s the question? I’m trying to query the URL and it’s failing, I want to know why this is.

1 answer

5


The problem is that you are trying to make a cross-Omain request via ajax, which is not allowed due to Policy of the same origin (unless the target domain supports CORS).

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

I don’t know if it’s viable for you, but an alternative is to create a file on your local server to serve as a proxy. This file would request the API and return the JSON to you. This way your ajax call would be 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 receive exactly what the API returns.

Browser other questions tagged

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