Trying to search wunderground locations with javas

2020-03-07 04:24发布

The code below doesn't work. Trying to search weather locations. When I search nothing happens.

<input type="text" id="query" /><button>search</button><br />
<div id="results">

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var url='http://autocomplete.wunderground.com/aq?format=JSON&query=';
var query;
    $('button').click(function(){
        query=$("#query").val();
        $.getJSON(url+query,function(json){
            $.each(json.results,function(i,location){
               $("#results").append('<p>'+location.name+'</p>');
            });
        });
    });
});
</script>

FYI I am very inexperienced at coding (copied script from another website)

2条回答
Melony?
2楼-- · 2020-03-07 05:00

If you want to make cross domain request, you have to that with JSONP, and you should append callback function for JSONP request as mentioned here in wunderground.com, try this.

$(document).ready(function() {
    var url = 'http://autocomplete.wunderground.com/aq?format=JSON&query=';
    var query;
    $('button').click(function() {
        query = $("#query").val();
        $.getJSON(url + query + '&cb=callbackfunc', function(json) {
            $.each(json.results, function(i, location) {
                $("#results").append('<p>' + location.name + '</p>');
            });
        });
    });
});​

UPDATE:

At first you should learn what is JSONP.

cb parameter is for JSONP callback function in wunderground API as you can see here in documentation.

If you still doesn't understand why you need to use jsonp callback function,

open these two links, and you will see what is the differences between them.

without cb paramater

with cb paramater

查看更多
甜甜的少女心
3楼-- · 2020-03-07 05:07

You can't pull data from remote sites using JavaScript for security reasons (see the same origin policy).

Work arounds involve CORS (limited browser support, not supported by that service), JSON-P (not obviously supported by that service) and using a proxy on your own server.

查看更多
登录 后发表回答