如何从 JSON 对象中检索带有坐标的变量

How to retrieve a variable with coordinates from a JSON object

我正在尝试获取具有名称和位置的对象 属性。我需要位置 属性 的坐标才能在该位置创建标记。 运行 然而,此代码导致 Uncaught SyntaxError: Unexpected token o in JSON at position 1。我在我的 PUT 方法中使用了 JSON.stringify(data)。

function getLocation(){
 var name = $("#username").val();
 console.log('getLocation()');
 if(name != ''){
  $.ajax({
   type: 'GET',
   url: '../../' + name,
      async: true,
      success:function(data){
       var oData = JSON.parse(data);
       var marker = new L.marker(oData.location);
    marker.addTo(map);
       $("#username").val('');
      },
   error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); }
  });
 }
}

$.ajax 使用默认的 dataType 设置将猜测响应的类型并已经解析它:

dataType (default: Intelligent Guess (xml, json, script, or html))

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

所以正如帕特里克·埃文斯所说,你的 data 已经转换为一个对象,你不需要使用 JSON.parse

可能是您的结果已经 JSON 解析了

  function getLocation(){
    var name = $("#username").val();
    console.log('getLocation()');
    if(name != ''){
      $.ajax({
        type: 'GET',
        url:  '../../' + name,
          async: true,
          success:function(data){
            var marker = new L.marker(data.location);
          marker.addTo(map);
            $("#username").val('');
          },
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); }
      });
    }
  }

或者如果你获得一个数组

  function getLocation(){
    var name = $("#username").val();
    console.log('getLocation()');
    if(name != ''){
      $.ajax({
        type: 'GET',
        url:  '../../' + name,
          async: true,
          success:function(data){
            var marker = new L.marker(data[0].location);
          marker.addTo(map);
            $("#username").val('');
          },
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); }
      });
    }