【问题标题】:On success of ajax post, how to send a POST request with JQuery .load() methodajax 发布成功后,如何使用 JQuery .load() 方法发送 POST 请求
【发布时间】:2013-10-01 22:02:10
【问题描述】:

在 Ajax 发布成功后,我希望处理程序中与 POST 关联的模板使用 JQuery 的 .load() 方法呈现。 GET 请求在 POST 成功后不断被调用……因此与 GET 关联的模板被呈现,而不是与 POST 关联的模板。感谢您提供的任何提示。

Javascript:

$(function() {  
    $(".topic_submit").click(function() {  
    var topic = $("#topic").val();
    refresh = 'false'
        $.ajax({  
            type: "POST",  
            url: "/mentorlist",  
            data: {'topic': topic},  
            success: function(dataString) {  
                $('#mentor_list').load('/mentorlist');
                console.log('**mentor_list div updated via ajax.**'); 
            }  
        });  
        return true;  
    });  
}); 

HTML 表单:

<form id="topic_search_form"  name="topic_search_form" action="">
 Topic:  <input id ="topic" type="text" name="topic" size="60" placeholder="Search by Keyword" />
<input type="submit" class="topic_submit" name="topic_submit" value="Search" >

【问题讨论】:

    标签: javascript ajax jquery web-development-server


    【解决方案1】:

    当您以这种方式调用.load() 而没有额外的数据时,您实际上只是调用了.get() 的简化版本。如果您尝试使用从帖子返回的数据,您应该这样做

        $.ajax({  
            type: "POST",  
            url: "/mentorlist",  
            data: {'topic': topic},  
            success: function(dataString) {  
                $('#mentor_list').html(dataString);
                console.log('**mentor_list div updated via ajax.**'); 
            }  
        });  
    

    【讨论】:

    • 这不是真的。 load() 仍然可以发起 POST 请求。见api.jquery.com/load
    • 我特意说了When you call .load() in that fashion without additional data。是的,如果你提供了额外的参数,你可以发帖。
    • @haim770 不需要对不起芽。令我印象深刻的是,您意识到自己在原始回复中多了一个 });。干得好:)
    • 谢谢@kpsuperplane!这就像一个魅力——我还在学习这个,但你能告诉我 ."html(dataString)" 是如何工作的而不是 .load() 吗? -谢谢
    • @MattEllis,还记得 success: function(dataString) 是怎么做到的吗?这样做是将来自该发布请求的响应放入该变量中。所以你所要做的就是将innerhtml(使用.html())更改为来自服务器的响应。基本上,success 函数在发布请求成功后被调用,并将响应放入该变量中:)
    【解决方案2】:

    您不需要两个后续请求即可将响应数据加载到您的#mentor_list,您只需调用一次load() 并使用POST,如下所示:

    $(".topic_submit").click(function()
    {
        var topic = $("#topic").val();
        refresh = 'false';
    
        $('#mentor_list').load('/mentorlist', { topic: topic });
    });
    

    【讨论】:

      【解决方案3】:

      .load() 确实允许 POST,但您必须给它一个数据对象...尝试给它一个新对象...

      $('#mentor_list').load('/mentorlist', {});
      

      【讨论】:

        猜你喜欢
        • 2015-09-07
        • 2010-10-10
        • 2012-07-23
        • 2018-09-07
        • 1970-01-01
        • 1970-01-01
        • 2015-10-03
        • 2014-12-09
        • 1970-01-01
        相关资源
        最近更新 更多