我正在尝试以特定方式发送或检索,但不确定故障出在哪里...
这是使用 JSON.stringify(test) 时的样子:
{"1":"<div class=\"test\">test1</div>","2":"<div class=\"test\">test2</div>","1":"<div class=\"test\">test1</div>"}
但是我的 ajax/json 返回看起来像这样:
["'1':'<div class='test'>test1</div>'","'2':'<div class='test'>test2</div>'","'3':'<div class='test'>test3</div>'"]
我需要在开头加上大括号,而“则不需要。
这是我发送和获取数据的方式。
测试.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);
以及检索它的 JavaScript:
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));
});
真的希望得到帮助......我被困住了。预先感谢:-)
最佳答案
您正在使用数组。正如凯文指出的那样,这是行不通的。您需要声明一个需要键值对的对象文字。
即
var myTest = {};
$.each(data, function (i, val) {
mytest[i] = val;
});
这是一个很好且更详细的解释。 How can I add a key/value pair to a JavaScript object?
关于javascript - 没有按照我想要的方式获取 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17707486/