2

我是 Json 和 Jquery 的新手。

今天我做了这个小代码,但它不起作用。我想我写得对,但我知道某处有一些小错误。你能帮我弄清楚吗?

    <!doctype html>
    <html lang="en">
    <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>

    <script>

    $(document).ready(function () {

    $(":button").click(function(){

     var add = $("#destination").val();

    $.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address= + add   +&sensor=false", function (data) {
        var output = "<ul>";


            output += "<li>"+ results.geometry.location.lat + " " + results.geometry.location.lng  + "</li>";
            output += "</ul>";

        document.getElementById("placeholder").innerHTML = output;
    });
    });
});
    </script>
    <body>

    <input type="text"  id="destination" /><button type="button">Search</button><br>
    <div id="placeholder"> </div>
</body>

</html>
4

3 回答 3

2

固定的。请注意,结果是一个数组。

<script>

$(document).ready(function () {

$(":button").click(function(){

 var add = $("#destination").val();

$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address= + add   +&sensor=false", function (data) {
    var output = "<ul>";


        output += "<li>"+ data.results[0].geometry.location.lat + " " + data.results[0].geometry.location.lng  + "</li>";
        output += "</ul>";

    document.getElementById("placeholder").innerHTML = output;
});
});

});

<input type="text"  id="destination" /><button type="button">Search</button><br>
<div id="placeholder"> </div>

于 2013-08-04T07:35:59.577 回答
0

您的 jquery 选择器不需要冒号,因为您指的是元素名称

$("button")

正如freakish 所说,在创建url 字符串时,您需要在使用“+”连接字符串之前关闭引号。

你发现你得到了一个数组。凉爽的。

如果你想看看,我做了一个小提琴。创建您的 json 请求并在浏览器中仔细检查它(Chrome 很好地呈现 json)有很大帮助。

我在 jsfiddle 上的解决方案

于 2013-08-04T07:53:00.603 回答
0

我想URL有错误。应该是:

"http://maps.googleapis.com/maps/api/geocode/json?address="+add+"&sensor=false"

因为add是前面定义的变量。

除此之外,您还应该这样做(因为您使用的是 jQuery):

$("#placeholder").html(output);

代替

document.getElementById("placeholder").innerHTML = output;

最后(如@pixelcdv 所述)你可能想要

$.getJSON(..., function (results) {

因为您results稍后使用,而不是data.

于 2013-08-04T07:32:28.520 回答