javascript - Not getting json the way I want -
i trying send or retrieve, not sure fault is, in specific way...
here how should when using json.stringify(test):
{"1":"<div class=\"test\">test1</div>","2":"<div class=\"test\">test2</div>","1":"<div class=\"test\">test1</div>"}
but ajax/json return looks this:
["'1':'<div class='test'>test1</div>'","'2':'<div class='test'>test2</div>'","'3':'<div class='test'>test3</div>'"]
i need curly brackets @ beginning , " not there.
here how send , data.
test.php
$test = array(); $test[] = array('id' => '1', 'name' => 'test1'); $test[] = array('id' => '2', 'name' => 'test2'); $test[] = array('id' => '3', 'name' => 'test3'); echo json_encode($test);
and javascript retrieves it:
var mytest = []; $.getjson('test.php', function(data){ $.each(data, function (i, val) { mytest.push("'"+val.id+"':'<div class='test'>"+val.name+"</div>'"); }); alert(json.stringify(mytest)); });
really hoping help... stuck. in advance :-)
in javascript code, you're creating array in results instead of object... instead of using []
, should use {}
, instead of using .push, should directly assign attributes of object mytest["1"] = whatever
. here's modified form of code...
var mytest = {}; $.getjson('test.php', function(data){ $.each(data, function (i, val) { mytest[val.id] = '<div class="test">'+val.name+'</div>'; }); alert(json.stringify(mytest)); });
Comments
Post a Comment