如何使用Ajax提交表单,然后显示带有警报的表单信息?

时间:2017-07-09 10:32:19

标签: jquery ajax

我想发送一个表单,然后一个警报显示表单中的信息。我想以这种方式显示提醒:你的FirstName是Mickey,LastName是Mouse!

<!DOCTYPE html>
<html>
<head>
<script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("button").click(function(){

        data:$("form").serialize();
        alert(data);
    });
});
</script>
</head>
<body>

<form action="">
  First name: <input type="text" name="FirstName" value="Mickey"><br>
  Last name: <input type="text" name="LastName" value="Mouse"><br>
</form>

<button>submit</button>



</body>
</html>

1 个答案:

答案 0 :(得分:1)

    $.ajax({
      type: "POST",
      url: "ajaxform.php", // url that the data need to go
      data: $("form").serialize(),
      success: function(data) {
          if (data) {
              alert("your first name is: " + $('input[name=FirstName]').val() + " Last name is: " + $('input[name=LastName]').val())
          }

      }
  });

如果要在数据对象中使用值,则尝试此操作,然后它将取决于对象。此外,您还需要将提交按钮放在表单中

&#13;
&#13;
$(document).ready(function(){

    $("form").submit(function(){
        alert("your first name is: " + $('input[name=FirstName]').val() + " Last name is: " + $('input[name=LastName]').val())// remove this alert when ajax code is working. it will not work here in the fiddle
        $.ajax({
      type: "POST",
      url: "ajaxform.php", // url that the data need to go
      data: $("form").serialize(),
      success: function(data) {
          if (data) {
              alert("your first name is: " + $('input[name=FirstName]').val() + " Last name is: " + $('input[name=LastName]').val())
          }

      }
  });
        return false;
    });
   
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

</head>
<body>

<form id="form" method="post" action="">
  First name: <input type="text" name="FirstName" value="Mickey"><br>
  Last name: <input type="text" name="LastName" value="Mouse"><br>
  <input type="submit">
</form>





</body>
</html>
&#13;
&#13;
&#13;