Fabio97 Fabio97 - 4 months ago 9
JSON Question

return data in a json object

I've got the following json object:

$dati = array(
"data" => array(
'address_complete'=>$data->results[0]->formatted_address,
'address_square'=>$data->results[0]->address_components[1]->long_name,
'location'=>$data->results[0]->address_components[2]->long_name,
'postal_code'=>$data->results[0]->address_components[7]->long_name,
'data_ora'=>$tmp_date
),
"str" => array("n".$i=>$array_db[username]),
"index" => $i
);


I want to show str data. So I've wrote:

... success:function(msg){
if(msg){
var j = "n"+2;
$("#location").html(msg.str.j);
}else{
$("#location").html('Not Available');
}
},


but the output is empty. Instead if I don't use variable j in $("#location").html(msg.str.j); but
$("#location").html(msg.str.n2);

it work correctly. Why this?

Answer

This is because you are trying to attach string to a Object.

You are trying to do something like this msg.str.'n2' which is not same as msg.str.n2.

I will give you working example right now:

var object = {
    name: 'Aleksandar',
    lastname: 'Djokic'
};
alert(object.name);

result of this is "Aleksandar"

Now this :

var object = {
    name: 'Aleksandar',
    lastname: 'Djokic'
};
var something = 'name';
alert(object.something);

Result of this alert is "undefined".

update: for array in object:

var object = {
    name: 'aleksandar',
    lastname: 'djokic',
    arr: ['first','second','third']
};
for(var i = 0; i<object.arr.length; i++) {
    alert(object.arr[i]);
}

if you want to get it by key then use :

var something = 'n2'; 
alert(msg.str[something]); 

Correct solution :

... success:function(msg){
        if(msg){
                var j = "n"+2;
                $("#location").html(msg.str[j]);
        }else{
            $("#location").html('Not Available');
        }
    },