ОК, Воломике! Я посмотрел на ваш код и было несколько проблем:
Во-первых, когда вы используете load
, он не заменяет выбранный узел, он заменяет его содержимое .
Итак, вы вызываете load для li
, но также возвращаете тот же li
в вашем результате AJAX. Впоследствии вы получаете это:
<li id="node-7">
<li id="node-7">
...
Кроме того, вы закрывали его двумя </ul>
тегами в строке ajax.php
38
вместо одного ul
и одного li
.
Итак, если вы исправите эти вещи, он должен начать работать. Тем не менее, я бы подошел к тому, что вы делаете, совершенно по-другому. Я надеюсь, что это поможет вам:
HTML
<ul id="tree">
<li id="node-1"><a href="#">Cat 1</a></li>
<li id="node-7"><a href="#">Cat 7</a></li>
</ul>
PHP
// You'll have to write the code, but get it into this format:
// Basically push each row of a `mysql_fetch_array` into a new array
$ret = array(
array('2', 'Cat 2'),
array('3', 'Cat 3')
);
// Then return it to the browser like this:
echo json_encode( $ret );
JS / JQuery
$(function(){
$("ul#tree li a").live('click', function(e){
e.preventDefault();
var $li = $(this).closest('li');
if( $li.find('ul').length ){
// Remove UL if it exists
$li.find('ul').remove();
} else {
// Get the ID
var id = $li[0].id.replace('node-','');
// Get the JSON for that id
$.getJSON('/ajax.php', { id: id }, function( data ){
// If data is not empty and it is an array
if(data && $.isArray( data )){
// Build our UL
var $ul = $("<ul></ul>");
// Loop through our data
$.each(data, function(){
// Build an LI, use `text()` to properly escape text
// then append to the UL
$('<li id="node-' + this[0] + '"><a href="#"></a></li>')
.find('a').text(this[1])
.end().appendTo($ul);
});
// Finally, add the UL to our LI
$ul.appendTo($li);
}
});
}
});
});