2015-06-21 88 views
0

我有我的AJAX形式,它的工作很棒。 我每次提交表格時都會返回<div id="message"></div>內的結果,但當我有多個表格時會變得複雜。所以我想知道如果他們是一種方式來表明內部形式什麼<div>返回消息。AJAX表單,傳遞返回消息

這裏是我的AJAX.js

$("form#ajaxForm").on("submit", function() { 
    var form = $(this), 
     url = form.attr("action"), 
     type = form.attr("method"); 
     data = {}; 


    form.find("[name]").each(function(index, value){ 
      var input = $(this), 
       name = input.attr("name"), 
       value = input.val(); 

      data[name] = value; 
    }); 
    $.ajax({ 
     url: url, 
     type: type, 
     data: data, 

     success: function(response) { 
      $("#message").html(response); //I would like to interactively switch the return div, from #message to like #message2 
      $("body, html").animate({ 
       scrollTop: $($("#message")).offset().top - 5000 
      }, 600); 
     } 
    }); 

    return false; 
}); 

在我想指明返回DIV是,像

<form action="../forms/add_event_form.php" method="post" id="ajaxForm"> 
    //Can I add an input somewhere here? To indicate where I want the return to go too? Like <input type="hidden" value="message2" name="return"> 
    <input type="text" class="formI" name="date" id="dateI" placeholder="Date"> 
    <input type="submit" name="submit" class="btn btn-primary" value="Add"> 
    </form> 

感謝您閱讀此形式。祝你有美好的一天!並且預先感謝您的回覆。

回答

0

是的,它不會自動工作,但您可以添加一些信息到窗體,然後用它來決定放置返回的HTML的位置。儘管如此,使用額外的輸入可能不是最好的方式,因爲它可以通過對DOM的影響小得多:在表單上具有屬性。

下面是一個如何做到這一點的例子。

$(".ajaxForm").on("submit", function(e) { 
 
    e.preventDefault(); 
 

 
    var form = $(this); 
 
    // using jQuery's `data()` to get an ID of response element from the 'data-response' attribute 
 
    var responseElementId = form.data("response"); 
 
    var response = $(responseElementId); 
 
    response.html(produceResponse(form)); 
 

 

 
    // function that produces some html response 
 
    // you'll use AJAX request to the server for that 
 
    // so don't mind its complexity or bugs 
 
    function produceResponse(form) { 
 
    var data = form.find("input").map(function(i, el) { 
 
     return "'" + el.name + "': " + el.value; 
 
    }); 
 
    return "<p>You've submitted:\n<pre>" + Array.prototype.join.call(data, ",\n") + "</pre></p>"; 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<h2>Form #1</h2> 
 
<form action="#" class="ajaxForm" data-response="#response1"> 
 
    <input name="first-name" type="text"> 
 
    <button>Submit</button> 
 
</form> 
 
<div id="response1"></div> 
 

 
<h2>Form #2</h2> 
 
<form action="#" class="ajaxForm" data-response="#response2"> 
 
    <input name="last-name" type="text"> 
 
    <button>Submit</button> 
 
</form> 
 
<div id="response2"></div>

這裏我用一個data屬性,因爲它是designed for cases like this:存儲與所述元素的任意數據,但沒有爲瀏覽器的任何定義的含義。訪問以這種方式存儲的數據非常方便,因爲它的HTML5 API非常方便,但由於IE的支持很低(它只從版本11開始),所以可以使用jQuery的method data()來做同樣的事情。