jQuery ajax问题

时间:2009-07-26 06:24:37

标签: jquery

我正在使用jQuery编写一些功能,我通常使用页面刷新/表单提交来处理。

基本上我使用jQuery的ajax提交表单。

<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>

<script type="text/javascript">

$(document).ready(function(){


    $("#show-comment-form").click(function(event){
        var ret =  $.post("post.php", $("#comment-form").serialize(), "", "html");
        $("#theComment").html("<strong>" + ret +"</strong>");
    });
});


</script>

</head>
<body>
Testing Stuff
<br /><a href="#" id="show-comment-form">Insert New Message</a><br />

    <div id="comment-form">
        <form name="form" id="form">
            <span>Enter Your Question Here</span>
            <textarea id="comment" name="comment"></textarea>
        </form>

    </div>

    <p id="theComment">

     avsailable
    </p>    


</body>

</html>

返回的对象是XMLHttpRequest。我操纵这个物体还是我可能不需要的东西。

我的问题是我希望让用户使用网页上的表单发布回复,但是在没有页面重新加载的情况下执行回复并将html添加到所有其他用户响应的开头。发布表单的页面打印出一些HTML但我无法在页面上显示该HTML,因为响应是XMLHttpRequest对象。我有点迷茫。有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:3)

您必须使用callback函数参数:

$("#show-comment-form").click(function(event){
    $.post("post.php", $("#comment-form").serialize(), function(ret){
      $("#theComment").html("<strong>" + ret +"</strong>");
    }, "html");
});

当异步请求结束时,该函数将被执行,其第一个参数是从服务器返回的数据。

答案 1 :(得分:2)

将函数指定为第三个参数,并且应该在回调中返回数据:

var ret = $ .post(“post.php”,$(“#comment-form”)。serialize(),function(data){ $(数据).appendTo( '主体'); });

您不需要与XHR对象进行交互。欲了解更多信息:

http://docs.jquery.com/Ajax/jQuery.post