我试图使用此示例使用AJAX提交HTML表单。

我的HTML代码:

<form id="formoid" action="studentFormInsert.php" title="" method="post">
    <div>
        <label class="title">First Name</label>
        <input type="text" id="name" name="name" >
    </div>
    <div>
        <label class="title">Name</label>
        <input type="text" id="name2" name="name2" >
    </div>
    <div>
        <input type="submit" id="submitButton"  name="submitButton" value="Submit">
    </div>
</form>


我的脚本:

<script type="text/javascript">
    $(document).ready(function() { 
        $('#formoid').ajaxForm(function() { 
            alert("Thank you for your comment!"); 
        }); 
    });
</script>


这不起作用,我什至没有收到警告消息
,当我提交时,我不想重定向到另一个页面,我只想显示警报消息。

有简单的方法吗?

PS:我有几个字段,我仅以两个为例。

评论

您不能取消“表单” HTML组件吗?并使用jquery在come按钮的点击处理程序上发布

#1 楼

AJAX的快速描述
AJAX是异步JSON或XML(在大多数新情况下为JSON)。因为我们正在执行ASYNC任务,所以我们很可能会为我们的用户提供更愉快的UI体验。在这种特定情况下,我们正在使用AJAX进行FORM提交。
很快,就有4个常规的Web操作GETPOSTPUTDELETE;它们直接与SELECT/Retreiving DATAINSERTING DATAUPDATING/UPSERTING DATADELETING DATA对应。默认的HTML / ASP.Net Webform / PHP / Python或任何其他form操作将“提交”,这是一个POST操作。因此,下面将全部描述执行POST。但是有时使用http时,您可能需要采取其他措施,并可能希望利用.ajax
我的代码专门为您(在代码注释中进行了描述):



 /* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $(this),
    url = $form.attr('action');

  /* Send the data using post with element id name and name2*/
  var posting = $.post(url, {
    name: $('#name').val(),
    name2: $('#name2').val()
  });

  /* Alerts the results */
  posting.done(function(data) {
    $('#result').text('success');
  });
  posting.fail(function() {
    $('#result').text('failed');
  });
}); 

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="formoid" action="studentFormInsert.php" title="" method="post">
  <div>
    <label class="title">First Name</label>
    <input type="text" id="name" name="name">
  </div>
  <div>
    <label class="title">Last Name</label>
    <input type="text" id="name2" name="name2">
  </div>
  <div>
    <input type="submit" id="submitButton" name="submitButton" value="Submit">
  </div>
</form>

<div id="result"></div> 





文档
来自jQuery网站$.post文档。
示例:使用ajax请求发送表单数据
$.post("test.php", $("#testform").serialize());

示例:使用张贴表单ajax并将结果放入div
<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form action="/" id="searchForm">
            <input type="text" name="s" placeholder="Search..." />
            <input type="submit" value="Search" />
        </form>
        <!-- the result of the search will be rendered inside this div -->
        <div id="result"></div>
        <script>
            /* attach a submit handler to the form */
            $("#searchForm").submit(function(event) {

                /* stop form from submitting normally */
                event.preventDefault();

                /* get some values from elements on the page: */
                var $form = $(this),
                    term = $form.find('input[name="s"]').val(),
                    url = $form.attr('action');

                /* Send the data using post */
                var posting = $.post(url, {
                    s: term
                });

                /* Put the results in a div */
                posting.done(function(data) {
                    var content = $(data).find('#content');
                    $("#result").empty().append(content);
                });
            });
        </script>
    </body>
</html>


重要说明
如果不使用OAuth或至少使用HTTPS(TLS / SSL),请不要将此方法用于安全数据(贷方)卡号,SSN,与PCI,HIPAA或登录相关的任何内容)

评论


@ abc123如何在其中设置授权请求标头?我尝试过beforeSend:function(xhr){xhr.setRequestHeader(“ Authorization”,“ *****”); xhr.setRequestHeader(“ contentType”,“ application / json; charset = UTF-8”); },但这不会设置任何标题

– mahendra kawde
2015年10月5日在6:52



@mahendrakawde,您需要利用$ .ajax,如果您愿意,我可以写一个例子,但这确实是一个单独的问题

–abc123
2015年10月6日,12:59

@ abc123我确实为此启动了线程。让我与您分享。

– mahendra kawde
2015年10月6日下午13:01

我们是否可以完全避免使用表单发布,而只是对按钮(不是任何表单div的html按钮)单击处理程序进行jquery发布。这样既不需要event.preventdefault吗?

– harshvchawla
18-09-19在7:24

@harshvchawla当然,但是从html元素提取的变量的选择查询是不同的

–abc123
18-09-25在20:20

#2 楼

var postData = "text";
      $.ajax({
            type: "post",
            url: "url",
            data: postData,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        })


评论


呼叫完成并从服务器收到200 OK时,将发生成功/完成功能

– Varun S
13年5月1日18:00



嗨,我说:$(document).ready(function(){$('#formoid')。submit(function(){var postData =“ text”; $ .ajax({type:“ post”,url:“ url”,数据:postData,contentType:“ studentFormInsert.php”,成功:function(responseData,textStatus,jqXHR){alert(“数据已保存”)},错误:function(jqXHR,textStatus,errorThrown){console.log( errorThrown);}})});它实际上不起作用..需要在php端进行任何修改吗?

–奥利维拉
2013年5月1日18:23



一个很好的例子并且写得很好,请发布一些答案,尽管不只是没有解释的示例代码。

–abc123
13年5月1日在18:23

我不知道如何将其与我要发布的表单联系起来

–彼得·卡莫达(Piotr Kamoda)
17 Mar 30 '17 at 12:31

为什么没有解释?

–丰富
18年2月1日在21:26

#3 楼

如果添加:

jquery.form.min.js

您可以简单地执行以下操作:
<script>
$('#myform').ajaxForm(function(response) {
  alert(response);
});

// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>


注意:
您可以按照上面的文章中的建议使用简单的$('FORM')。serialize(),但这不适用于文件输入... ajaxForm()可以。