$.getJSON parece regresar como una cadena literal con objetos anidados

Hello I am new to JSON and have run into some issues.

I am requesting some information using jquery's $.getJSON method like so:

function getPlayerPositions(type) { //left/top/move
    var loadUrl = "../php/client_communication/relay_positions.php";
    var playerPos = [];

    $.ajaxSetup ({
        cache: false,
        async: false
    });

    $.getJSON( loadUrl, { type: type } )
    .done(function( data ) {
            useReturnData(data);
    })
    .fail(function( jqxhr, textStatus, error ) {
      var err = textStatus + ', ' + error;
      console.log( "Request Failed: " + err);
    });

    function useReturnData(data){
        playerPos = data;
        alert("response: "+playerPos);
    };

    //reset to asynchronous ajax from now on
    $.ajaxSetup ({
        async: true
    });
    alert(playerPos[0]);
    return playerPos;
}

And when my function is ran previously to this time I receive the correct JSON encoded data that I can then access via my "playerPos" array. (ie. alert(playerPos[4]))

But this time I am receiving data that contains multiple nested objects:

This is the ajax response alerted:

response: [{"Position":"LB","ID":" 2","x-offset":" 0","y-offset":" 0","Stats":{"ID":"2","IMG":"/images/player_avatars/player_test.png","First_Name":"Daniel","Surname":"Vernall","Nickname":"Tall Tree","number":"25","Fav_Pos_1":"LB","Fav_Pos_2":"CB","team":"A","SPEED":"100","AGILITY":"100","STRENGTH":"100","JUMP":"100","MARKING":"100","STAMINA":"100","LEADERSHIP":"100","ADAPTABILITY":"100","RESTRAINT":"100","INJURY_PRONE":"100","HEAL_TIME":"100","MORALE":"100","AGGRESSIVENESS":"100","PASSING":"100","SHOOTING_ACCURACY":"100","SHOOTING_POWER":"100","HEADING":"100","MISC_BODY":"100","POSITIONING":"100","FIRST_TOUCH":"100","LONG_DISTANCE":"100","STRONG_FOOT":"0","CONTROL":"100","CURLING":"100","CHIPPING":"100","VOLLEYING":"100","SET_PIECES":"100","THROW_INS":"100","REFLEXES":"100","ONE_ON_ONES":"100","AERIAL_ABILITY":"100","CATCHING":"100","COORDINATION":"100","THROWING":"100","coordX":0,"coordY":0,"yellowCards":0,"redCards":0,"shotsOnTarget":0,"shotsOffTarget":0,"goals":0,"assists":0,"completedPasses":0,"incompletePasses":0,"tackles":0,"timesTackled":0,"intercepts":0,"intercepted":0,"badReceive":0}},{"Position":"LCB","ID":" 3","x-offset":" 0","y-offset":" 0","Stats":{"ID":"3","IMG":"/images/player_avatars/player_test.png","First_Name":"Teddy","Surname":"Vernall","Nickname":"Bear","number":"11","Fav_Pos_1":"ST","Fav_Pos_2":"CAM","team":"A","SPEED":"100","AGILITY":"100","STRENGTH":"100","JUMP":"100","MARKING":"100","STAMINA":"100","LEADERSHIP":"100","ADAPTABILITY":"100","REST...,"SET_PIECES":"100","THROW_INS":"100","REFLEXES":"100","ONE_ON_ONES":"100","AERIAL_ABILITY":"100","CATCHING":"100","COORDINATION":"100","THROWING":"100","coordX":0,"coordY":0,"yellowCards":0,"redCards":0,"shotsOnTarget":0,"shotsOffTarget":0,"goals":0,"assists":0,"completedPasses":0,"incompletePasses":0,"tackles":0,"timesTackled":0,"intercepts":0,"intercepted":0,"badReceive":0}},{"Position":"GK","ID":" 12","x-offset":" 0","y-offset":" 0","Stats":{"ID":"12","IMG":"/images/player_avatars/player_test.png","First_Name":"Rumple","Surname":"Stiltskin","Nickname":"Rumpy Pump Stink","number":"29","Fav_Pos_1":"CDM","Fav_Pos_2":"LB","team":"A","SPEED":"100","AGILITY":"100","STRENGTH":"100","JUMP":"100","MARKING":"100","STAMINA":"100","LEADERSHIP":"100","ADAPTABILITY":"100","RESTRAINT":"100","INJURY_PRONE":"100","HEAL_TIME":"100","MORALE":"100","AGGRESSIVENESS":"100","PASSING":"100","SHOOTING_ACCURACY":"100","SHOOTING_POWER":"100","HEADING":"100","MISC_BODY":"100","POSITIONING":"100","FIRST_TOUCH":"100","LONG_DISTANCE":"100","STRONG_FOOT":"50","CONTROL":"100","CURLING":"100","CHIPPING":"100","VOLLEYING":"100","SET_PIECES":"100","THROW_INS":"100","REFLEXES":"100","ONE_ON_ONES":"100","AERIAL_ABILITY":"100","CATCHING":"100","COORDINATION":"100","THROWING":"100","coordX":0,"coordY":0,"yellowCards":0,"redCards":0,"shotsOnTarget":0,"shotsOffTarget":0,"goals":0,"assists":0,"completedPasses":0,"incompletePasses":0,"tackles":0,"timesTackled":0,"intercepts":0,"intercepted":0,"badReceive":0}}]

Javascript seems to not view these as individual objects:

When alerting playerPos[4] for example it will simply alert the 4th character in the string above.

I realise the above is very difficult to read but I wanted to show you an actual copy of the alert.

This is the bit from the php file it accesses:

if($type=="db_request"){
    $team = new Team;
    $team = $team->buildTeam(101, 'A');
    ChromePhp::log($team);

    $response = json_encode($team);
}

And my log above looks like this:

Print Screen of my Console Log

So you can see that the php file views "$team" as containing multiple nested objects

¿Alguna idea?

preguntado el 10 de septiembre de 13 a las 00:09

No use $.ajaxSetup when it's only for a single request. Put such parameters in the option object of $.ajax. And don't use SJAX at all!!! -

@Bergi I originally used SJAX as I needed to wait for the response before I could continue drawing on the canvas, but I'm going to change my drawing function to check for the values itself. This was just a simple way to get functionality in the testing/early development stages. -

Now have you got any help for my question? -

No idea what's happening. Either you are double-encoding it on the server side (like echo json_encode($response);) or jQuery does something unexpected. Could you please post the HTTP as seen in the devtools' network inspector? -

Sorry not been developing long what do you mean by "Could you please post the HTTP as seen in the devtools' network inspector?" I'm not familiar with the devtools' network inspector. I don't think I'm double encoding the response. -

3 Respuestas

Seems like you're double-encoding the object (with something like echo json_encode($response);). jQuery would then parse the JSON-encoded string to the JSON-encoded object string…

You can check for such serverside failure by inspecting the effective HTTP response in your browser's network inspector (Chrome devtools, Libélula de ópera, Firebug).

Respondido el 10 de Septiembre de 13 a las 00:09

"Stats":{
"ID":"3",
"IMG":"/images/player_avatars/player_test.png",
"First_Name":"Teddy",
"Surname":"Vernall",
"Nickname":"Bear",
"number":"11",
"Fav_Pos_1":"ST",
"Fav_Pos_2":"CAM",
"team":"A",
"SPEED":"100",
"AGILITY":"100",
"STRENGTH":"100",
"JUMP":"100",
"MARKING":"100",
"STAMINA":"100",
"LEADERSHIP":"100",
"ADAPTABILITY":"100",
"REST...,"SET_PIECES":"100",
"THROW_INS":"100",
"REFLEXES":"100",
"ONE_ON_ONES":"100",
"AERIAL_ABILITY":"100",
"CATCHING":"100",
"COORDINATION":"100",
"THROWING":"100",
"coordX":0,
"coordY":0,
"yellowCards":0,
"redCards":0,
"shotsOnTarget":0,
"shotsOffTarget":0,
"goals":0,
"assists":0,
"completedPasses":0,
"incompletePasses":0,
"tackles":0,
"timesTackled":0,
"intercepts":0,
"intercepted":0,
"badReceive":0
}

ver el SyntaxError: Unexpected token S

Su SET_PIECES has broken out of the json making it invalid.

Respondido el 10 de Septiembre de 13 a las 00:09

That is only happening because of the alert(). Chrome will put ellipsis in the middle of alerted strings when they're too long to display. - Bergi

I don't see this syntax error myself, not sure where you got it from. The questions actually been answered in the comments and I'm waiting for Bergi to move it to an answer. I was double encoding the response. - Kyohei Kaneko

Ah see Bergi's comment for your syntax error! Thanks for commenting though! - Kyohei Kaneko

Thanks @bergi, My apologies! - Hidra IO

I know this is already answered but I noticed a few performance tips that may help quiet a bit. Avoiding nested functions when at all possible really can help speed up the application.

function getPlayerPositions(type) { //left/top/move
var loadUrl = "../php/client_communication/relay_positions.php";
var playerPos = [];

$.ajax( loadUrl, { type: type, async: false, cache: false, dataType: "json"  } )
    .done(function( data ) {
        playerPos = data;
        alert("response: "+playerPos);
    })
 .fail(function( jqxhr, textStatus, error ) {
      var err = textStatus + ', ' + error;
      console.log( "Request Failed: " + err);
   });

    alert(playerPos[0]);
    return playerPos;
}

MÁS INFORMACIÓN aquí

respondido 24 mar '14, 21:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.