Ajax and Google Places API getting json

Ajax and Google Places API getting json

本文关键字:getting json API Places and Google Ajax      更新时间:2023-09-26

我正在制作一个简单的页面,您可以在文本框中输入城市名称,它会显示有关它们的基本信息(地址,名称等)。我在使用 Google Places API 时遇到问题。这就是我到目前为止所拥有的

餐厅.html

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Restaurant Search</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="jquery.js"></script>
        <script src="functions.js"></script>
        <script>
            $(document).ready(function(){
                getRestaurants();
            });
        </script>
    </head>
    <body>
        <div class="main">
            <form>
                Enter city name: <input id="city" type="text" name="cityname"><input id="btn" type="submit" value="Search">
            </form>
            <div id="error">
                The search field cannot be left empty!
            </div>
        </div>
        <div id="header">
        </div>
        <div id="items">
        </div>
    </body>
</html>

函数.js

function getRestaurants(){
    $("#btn").click(function(){
        if ($("#city").val().length==0){
            $("#error").css("display","block");
        }else{
            $("#error").css("display","none");
            var cityname = $("#city").val();
            var search_string = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+"+cityname+"&sensor=false&key=KEYKEYKEY";
            $.ajax({
                url: search_string
            }).done( function ( data ) {
                res ="";
                var obj = jQuery.parseJSON(data);
                $(obj).each(function(){
                    res+=this.name;
                });
                $("#items").text(res);
            });
        }
    });
}

风格.css只有这个在里面

#error{
    display: none;
}

问题出在哪里?

请参阅此链接https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform只需复制代码并根据您的需要进行定制