使用AJAX成功函数来预先添加内容

时间:2013-07-08 13:08:24

标签: jquery ajax

我正在使用JQuery和AJAX来提交和处理表单。我想在处理表单中添加内容(AJAX url:comment.php)。我怎样才能做到这一点?我知道我必须使用Success:function()。

我的AJAX:

$.ajax({
    type: "POST",
    url: "comment.php",
    data: dataString,
    success: function () {
        //code to prepend the content from comment.php
    }
}); 

我的评论.php文件:

//Some processing code

<p> Success!! </p>

谢谢!

3 个答案:

答案 0 :(得分:2)

您只需添加PHP脚本返回的内容:

$.ajax({  
    type: "POST",  
    url: "comment.php",  
    data: dataString,
    success: function(data) {
        $('#elementID').prepend(data); // prepends "hello kitty"
    }
});

Comment.php

<?php
    // process form or whatever
    echo "hello kitty";
?>

请注意,PHP文件的任何输出都将返回到$ .ajax

答案 1 :(得分:0)

您可以使用.prepend()方法将html内容添加到元素

$.ajax({  
    type: "POST",  
    url: "comment.php",  
    data: dataString,
    dataType: 'html',
    success: function(html) {
        //code to prepend the content from comment.php
        $('#myelement').prepend(html);
    }
});

答案 2 :(得分:0)

在Comment.php文件中:

<?php echo "<p> Success!! </p>"; ?>

在你的ajax函数中进行以下更改:

$.ajax({  
    type: "POST",  
    url: "comment.php",  
    data: dataString,
    success: function(resp) {
        $("#msg").prepend(resp);
    }
});

将以下div代码放在要显示消息的位置。

<div id="msg"></div>