如何将JSON数据加载到id="hello"中

3

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>doers.lk</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <style type="text/css" media="screen">

    </style>
    </head>
    <body>
      <p id="hello"></p>
    </body>
    </html>

JQUERY

$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {
  alert('Latitude: ' + data.latitude +
        '\n Longitude: ' + data.longitude +
        '\n Country: ' + data.address.country);
});

点此查看演示

我想将这个json数据加载到id为"hello"的元素中。有更好的方法吗?

3个回答

1
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {
  $("#hello").html('Latitude: ' + data.latitude +
        '\n Longitude: ' + data.longitude +
        '\n Country: ' + data.address.country);
});​

请查看这个代码片段:http://jsfiddle.net/d4hGj/1/


最好使用本地的jQuery方法$(...).html(),这样不要混合使用本地js和jQuery,更加清晰。 - Christoph

1

jQuery提供了.html()方法,让您可以获取/设置元素的内容。在回调函数中,您可以通过元素的ID选择该元素,并使用.html()方法添加您的内容。

$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {
  $("#hello").html('Latitude: ' + data.latitude +
        '<br /> Longitude: ' + data.longitude +
        '<br /> Country: ' + data.address.country);
});​

工作示例


<script> $("#success").load("/id.html", function(response, status, xhr) { if (status == "error") { var msg = "Sorry but there was an error: "; $("#error").html(msg + xhr.status + " " + xhr.statusText); } }); var d = new Date(); var x = document.getElementById("demo"); x.innerHTML=d.toLocaleDateString(); </script> - sami
我正在使用ajax加载id.html。(id.html) 包含我的上面的html和json代码,但现在这两种方法都无法工作。 - sami
@KayleeMackenzie 那可能是一个新问题的主题,我建议您提出一个新问题,在其中描述您的新问题。 - Christofer Eliasson

1

这里演示

jQuery 代码

$.getJSON('http://smart-ip.net/geoip-json/?callback=?', function (data) {
    $("#hello").html('Latitude: ' + data.latitude +
        '<br /> Longitude: ' + data.longitude +
        '<br /> Country: ' + data.countryName);
});

html

使用smart-ip.net比wipmania.com更好


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接