Norman
Norman

Reputation: 6365

Right way to handle json data without looping in jQuery

What is the right way to handle json data without looping? The data that comes in is a json array like this: Object {idPri="1",idSec="2"}

I'll be using jQuery's $.ajax to do this

$.ajax({
  type:"GET",
  url:"testUserData.php",
  data:data,
  dataType:'json',
  success: function(userData) {
    $('.h2[data-id="'+idPri+'"]').find('span[data-sec="'+idSec+'"]').hide();
  }
}

I intend putting the idPri and idSec from the json array into the idPri and idSec inside the success function. What is the right way to do this? The size of that json array never changes, only the values change.

I presently do: userData.idPrid and userData.idSec

Upvotes: 0

Views: 160

Answers (2)

Brigand
Brigand

Reputation: 86230

idPri is not a variable, it's a property of an object. jQuery passes the object to your success handler, and you call that object userData. To access it you can do userData.idPri or userData["idPri"].

$.ajax({
    type:"GET",
     url:"testUserData.php",
    data:data,
dataType:'json',
success: function(userData){
    $('.h2[data-id="'+userData.idPri+'"]').find('span[data-sec="'+userData.idSec+'"]').hide();
},

Upvotes: 1

gherkins
gherkins

Reputation: 14983

I presently do: userData.idPrid and userData.idSec

Wouldn't that work, then?

success: function(userData){
    $('.h2[data-id="'+userData.idPri+'"]').find('span[data-sec="'+userData.idSec+'"]').hide();
}

function(userData) passes the result object to your callback function, not making its properties available...

Upvotes: 1

Related Questions