开发者

How do I append an LI to an UL using jQuery forms.js

I have multiple forms on a page and i'm trying to use jQuery form.js to save each comment that is posted and then append the comment to the UL afterwards. The save part of it is working fine. However, I am having trouble getting the comment to update the UL correctly. See code below:

//My Form
<form method="post" action="includes/answer.php" id="respond">
<input name="key_id" id="key_id" type="hidden" value="'.$row['thekey'].'" />
<textarea name="comment" id="comment"></textarea>
</form>

//The UL
<ul id="'.$row['thekey'].'" class="answer"></ul>

//The jQuery
$(document).ready(function() {
    jQuery('form').ajaxForm({
        target: 'ul',
        success: function(data) {
            $('ul#' + data.id).prepend("<li style='display:none'>"+data.comment+"</li>").fadeIn('slow');
            $("ul#" + data.id +"li:first").fadeIn();
        }
    });
});

//Postback Code
    $message = strip_tags(mysql_real_escape_string($_POST['comment']));
    $id = strip_tags(mysql_real_escape_string($_POST开发者_Go百科['key_id']));

    $sql_id = 'SELECT id FROM questions WHERE thekey = "'.$id.'"';
    $select_result = mysql_query($sql_id);

    if($select_result) {
        $row = mysql_fetch_array($select_result);
        $sql = 'INSERT INTO answers (answer, question_id) VALUES("'.$message.'", '.$row['id'].')';
        $result = mysql_query($sql);

        if($result) {
            print json_encode(array("id" => $id, "comment" => $message));
        }
    }

This is currently outputting an array that looks something like {"id":"sadfasdf2","comment":"ds"} in place of the ul tags. How can I get it to output the actual comment in a LI?


Change:

$('ul#' + data.id).prepend("<li style='display:none'>"+data.comment+"</li>").fadeIn('slow');

to:

$('ul#' + data.id).prepend($("<li></li>").text(data.comment).hide()).fadeIn('slow');

A bit explanation:

$("<li></li>") is how you create a new element. Then you can .text(content) on that element to set the content (.html(htmlcode) also works). .hide() is the same as style="display:none".

EDIT: owh and also, remove the target: 'ul', .. it's the config that tells ajaxForm to directly inject the response into the UL tag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜