开发者

Appending HTML to specific DOM after ajax call

In my php page, I've three lists ul#line, ul#comment, ul#vote.

I'm going to make an ajax call, something like

           $.ajax({
        type: "POST",
        url: "ajax.php",
        data: dataString,

        cache: false,
        success: function(html){
            $("ul#line").append(html);
            $("ul#lineli:last").fadeIn("slow");
    }

Ajax.php is something like

if(isset($line)){
    echo $line;
} elseif(isset($comment)){
    echo $comment;
} elseif (isset($vote)){
    echo $vote;
} else {
   //do nothing;
}

What I want is, if the echoed out HTML is $line, it'll be appended to ul#line; if it is $comment, it'll be appended to ul#comment; if it is $vote, it'll be appended to ul#vote.

The current ajax call appends only at ul#line.

开发者_Go百科

What do I need to change to achieve this??


php

class DataObject
{
    public $Type;
    public $Text;
}
    $json=new DataObject();

if(isset($line)){
    $json->Type="line";
    $json->Text=$line;
    return json_encode($json);
} elseif(isset($comment)){
    $json->Type="comment";
    $json->Text=$comment;
    return json_encode($json);
} elseif (isset($vote)){
    $json->Type="vote";
    $json->Text=$vote;
    return json_encode($json);
} else {
   //do nothing;
}

javascript

    $.ajax({
    type: "POST",
    url: "ajax.php",
    dataType: 'json',  //add data type
    data: dataString,    
    cache: false,
    success: function(data){
        $("ul#"+data.type).append(data.text);
        $("ul#"+data.type+"li:last").fadeIn("slow");
     }


I would pass back the information as JSON. Have something like:

{updateList : nameOfList, output: $line/$output/$vote }

Then on success you could do something like

$('#'+html.updateList).append(html.output);

You have to make sure to let jQuery know that you are sending and to accept json as the type back though.


You need some way to differentiate the values of $line and $comment.

I'd suggest sending back JSON from your PHP script:

if(isset($line)){
    echo '{"line" : ' . json_encode($line) . '}';
} elseif(isset($comment)){
    echo '{"comment" : ' . json_encode($comment) . '}';
} elseif (isset($vote)){
    echo '{"vote" : ' . json_encode($vote) . '}';
} else {
   //do nothing;
}

Note: PHP isn't my strongest language so there might be a better way to generate the JSON response

success: function(data){
           if(data.line) {
              $("ul#line").append(html);
              $("ul#lineli:last").fadeIn("slow");
           }
           else if(data.comment) {
              $("ul#comment").append(html);
              $("ul#commentli:last").fadeIn("slow");
           }
        }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜