使用 AJAX 提交表单将表单数据传递给 PHP,无需刷新页面 [英] Form submit with AJAX passing form data to PHP without page refresh

查看:39
本文介绍了使用 AJAX 提交表单将表单数据传递给 PHP,无需刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么这段代码不起作用?

Can anyone tell me why this bit of code isn't working?

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {
        $('form').bind('submit', function () {
          $.ajax({
            type: 'post',
            url: 'post.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });
          return false;
        });
      });
    </script>
  </head>
  <body>
    <form>
      <input name="time" value="00:00:00.00"><br>
      <input name="date" value="0000-00-00"><br>
      <input name="submit" type="button" value="Submit">
    </form>
  </body>
</html>

当我推送提交时什么也没有发生.在接收 php 文件中,我使用 $_POST['time'] 和 $_POST['date'] 将数据放入 mysql 查询中,但它只是没有获取数据.有什么建议?我假设这与提交按钮有关,但我无法弄清楚

When I push submit nothing happens. In the receiving php file I'm using $_POST['time'] and $_POST['date'] to put the data in a mysql query but it's just not getting the data. Any suggestions? I'm assuming it's something to do with the submit button but I can't figure it out

推荐答案

ajax请求后提交表单.

The form is submitting after the ajax request.

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'post.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form>
      <input name="time" value="00:00:00.00"><br>
      <input name="date" value="0000-00-00"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

这篇关于使用 AJAX 提交表单将表单数据传递给 PHP,无需刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆