Jquery 动态创建LIs不会';I don’我不想工作
我有一个symfony2函数,从模板中通过AJAX调用。这就是功能:Jquery 动态创建LIs不会';I don’我不想工作,jquery,html,symfony,Jquery,Html,Symfony,我有一个symfony2函数,从模板中通过AJAX调用。这就是功能: /** * Get subcategories based on $parent_id parameter * * @Route("/category/subcategories/{parent_id}", name="category_subcategories", options={"expose"=true}) * @Method("GET") */ public function getCategories(
/**
* 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);
}
}
});
});
});
$(函数(){
$(“a.step”)。单击(函数(){
var id=$(this.attr('data-id');
$.ajax({
键入:“GET”,
url:Routing.generate('category_subcategories',{parent_id:id}),
数据类型:“json”,
成功:功能(数据){
如果(data.length!=0){
var LIs=“”;
$。每个(数据[0],函数(i,v){
LIs+='';
});
$(#categories').html(LIs);
}
}
});
});
});
但它不起作用,因为只显示JSON数组的第一个元素,我的代码中有什么错误?有什么建议吗?太棒了,它现在可以工作了,没有看到
[0]
和解决方案,非常感谢
$.each(data[0], function(i, v) {
LIs += '<li><a class="step" data-id="' + i + '" href="#">' + v + '</a></li>';
});
$.each(data, function(index, value) {
$.each(value, function(i, v) {
LIs += '<li><a class="step" data-id="' + v + '" href="#">' + v + '</a></li>';
}
});