convert complex json din php in ajax

Discutii si intrebari legate de scripturi si functii JavaScript, jQuery si Ajax, cod JavaScript in general.
sterica
Mesaje: 285

convert complex json din php in ajax

Salutare,
In php am urmatorul cod:

Cod: Selectaţi tot

$element1 = fnc1 ($var1, $var2); // returneaza un string 'test test test'
$element2 = fnc2 ($var1, $var2); // returneaza un string '["test", "test", "test"]'
$element3 = fnc3 ($var1, $var2); // returneaza un string '{name: 'test', data: [1,2,3,4,]}'  (nu stiu cat de utile sunt { } )

echo json_encode(

    array("element1" => "$element1",
             "element2" => "$element2",
             "element3" => "$element3")
);

// echo json_encode returneaza:
{"element1": "test test test", 
 "element2": "[\"test\", \"test\", \"test\"]",
 "element3": "{name: 'test', data: [1,2,3,4,] }"}
?>
echo returnat din php il preiau cu ajax sub aceasta forma:

Cod: Selectaţi tot

...
function (result) {
// result in consola arata: { element1: "test test test", element2: "["test", "test", "test"]", element3: "{name: 'test', data: [1,2,3,4,]}"}
	var div1 = result.element1; // prima cheie o foloesc ca string
	var chart1 = result.element2; // a doua cheie o folosesc ca un array de forma ['test', 'test', 'test']
        var chart2 = result.element3; // a treia cheie o folosesc ca un array de forma [{ name: 'test', data: [1,2,3,4] }]

//pentru a transforma chart1 din string in array
chart1 = JSON.parse(chart1);

}

Cum pot transforma si variabila chart2 din:
"{name: 'test', data: [1,2,3,4,] }"
intr-un array
[{ name: 'test', data: [1,2,3,4] }]

Multumesc!

MarPlo Mesaje: 4343
Salut
Valoarea de la result.element3 nu e un sir json valid.
Ar trebui modificat in php ca fnc2() si fnc3() sa returneze array, sa ai asa:

Cod: Selectaţi tot

$element1 = fnc1($var1, $var2); // returneaza un string 'test test test'
$element2 = fnc2($var1, $var2); // returneaza un array ["test", "test", "test"]
$element3 = fnc3($var1, $var2); // returneaza un array [name=>'test', data=>[1,2,3,4,]]

echo json_encode(['element1'=>$element1, 'element2'=>$element2, 'element3'=>$element3]);
echo json_encode() returneaza:

Cod: Selectaţi tot

{
"element1": "test test test", 
"element2": ["test", "test", "test"],
"element3": {name:"test", data:[1,2,3,4,]}
}

Iar in ajax:

Cod: Selectaţi tot

function(result){
// result in consola arata: {element1:"test test test", element2:["test", "test", "test"], element3:{name:"test", data:[1,2,3,4,]}}
  var div1 = result.element1; // prima cheie, un string
  var chart1 = result.element2; // a doua cheie, un array de forma ['test', 'test', 'test']
  var chart2 = result.element3; // a treia cheie, un obiect de forma {name: 'test', data: [1,2,3,4]}
}

Subiecte similare