为什么我的JSON数据会发生变化?

时间:2017-01-22 15:47:51

标签: jquery json

我试图将我的json数据location参数传递给assignLocationValuesconsole.log。当我记录location.loc时,它显示两个看起来像这样的值:4,2394,5,3023。当我从中获取值时:location.loc[1]并记录它。价值变化,而不是5,3023变为1.发生了什么?

编辑:想通了。我真的以为这是一个阵列。太奇怪...............

$(document).ready(function() {
getLocation();

function getLocation() {

  $.get("http://ipinfo.io", function(location) { 

    assignLocationValues(location.loc[0], location.loc[1], location.city, location.region, location.country );

    function assignLocationValues(lat, lon, city, region, country){

      console.log(location.loc);
      console.log(lat);
    };
  }, 'jsonp');
};
});

2 个答案:

答案 0 :(得分:0)

将其放在正文标记底部的脚本标记中(document.ready是昨天的新闻)

function assignLocationValues(obj_location){

  var loc = obj_location;

  var _city = loc.city;
  var _country = loc.country;
  var _hostname = loc.hostname;
  var _ip = loc.ip;
  //....
  console.log(_ip);

};

function getLocation() {
  $.get("http://ipinfo.io/json", function(location) {
      assignLocationValues(location);
    });
}

getLocation();

答案 1 :(得分:-1)

试试这个:http://jsbin.com/IDebUfu/1/edit?html,js,output

$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
    var table_body = "";
    $.each(data, function(k, v) {
    table_body += "<tr><td>" + k + "</td><td><b>" + v + "</b></td></tr>";
    });
    $("#GeoResults").html(table_body);
});