简体   繁体   中英

How to retrieve a variable with coordinates from a JSON object

I'm trying to GET an object with a name and a location property. I need the coordinates of the location property to create a marker at that location. Running this code however results in Uncaught SyntaxError: Unexpected token o in JSON at position 1. I used JSON.stringify(data) in my PUT method.

 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 with default dataType setting will guess the type of response and parse it already:

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

So as Patrick Evans mentioned, your data is already converted to an object, you do not need to use JSON.parse .

Could be your result is already JSON parsed the

  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'); }
      });
    }
  }

or if you obtain an array

  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'); }
      });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM