basic Javascript jquery json Html

basic Javascript jquery json Html

本文关键字:Html json jquery Javascript basic      更新时间:2023-09-26

我是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>

已修复。请注意,结果是一个数组。

<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>

我想URL中有一个错误。可能应该是:

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

因为CCD_ 1是先前定义的变量。

其他你也应该做的事情(因为你使用的是jQuery):

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

而不是

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

最后(正如@pixelcdv所指出的)你可能想要

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

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

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

$("button")

正如fretash所提到的,在创建url字符串时,您需要在使用"+"连接字符串之前加上引号。

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

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

我在jsfiddle 上的解决方案