Trying to search wunderground locations with javascript, jquery, and html

佐手、 提交于 2019-12-03 22:27:02

问题


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)


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/10518913/trying-to-search-wunderground-locations-with-javascript-jquery-and-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!