AJAX表单,传递返回消息

时间:2015-06-21 20:42:11

标签: javascript php jquery ajax forms

我的AJAX表单效果很好。 每次我提交表单它都会在<div id="message"></div>内返回结果,但是当我有多个表单时它会变得复杂。所以我想知道他们是否可以在表单中指明要将消息返回到<div>的内容。

这是我的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>

感谢您阅读本文。祝你有美好的一天!并提前感谢您的回复。

1 个答案:

答案 0 :(得分: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()来做同样的事情。