2015-06-21 82 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()来做同样的事情。