我有一个从模板中通过AJAX调用的Symfony 2函数。这是功能:
/**
* Get subcategories based on $parent_id parameter
*
* @Route("/category/subcategories/{parent_id}", name="category_subcategories", options={"expose"=true})
* @Method("GET")
*/
public function getCategories($parent_id = null) {
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('CategoryBundle:Category')->findBy(array("parent" => $parent_id));
$subcategories = array();
foreach ($entities as $entity) {
$subcategories[] = array($entity->getId() => $entity->getName());
}
$response = new JsonResponse();
$response->setData($subcategories);
return $response;
}
该函数返回如下的JSON:
[{"27":"Test10"},{"28":"Test11"},{"29":"Test12"}]
所以我编写了这个jQuery函数来解析和显示元素:
$(function() {
$("a.step").click(function() {
var id = $(this).attr('data-id');
$.ajax({
type: 'GET',
url: Routing.generate('category_subcategories', {parent_id: id}),
dataType: "json",
success: function(data) {
if (data.length != 0) {
var LIs = "";
$.each(data[0], function(i, v) {
LIs += '<li><a class="step" data-id="' + i + '" href="#">' + v + '</a></li>';
});
$('#categories').html(LIs);
}
}
});
});
});
但它没有用,因为只显示了JSON数组的第一个元素,我的代码出了什么问题?有什么建议吗?
答案 0 :(得分:1)
$.each(data[0], function(i, v) {
LIs += '<li><a class="step" data-id="' + i + '" href="#">' + v + '</a></li>';
});
此处data[0]
为{"27":"Test10"}
,但您想要的是data
。
试试这个:
$.each(data, function(index, value) {
$.each(value, function(i, v) {
LIs += '<li><a class="step" data-id="' + v + '" href="#">' + v + '</a></li>';
}
});