Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用AJAX/jQuery/JavaScript提交表单?_Javascript_Php_Jquery_Ajax_Forms - Fatal编程技术网

如何使用AJAX/jQuery/JavaScript提交表单?

如何使用AJAX/jQuery/JavaScript提交表单?,javascript,php,jquery,ajax,forms,Javascript,Php,Jquery,Ajax,Forms,我有一个PHP网站,它有很多表单可以在提交时转到某些页面。所以它们看起来像这样: <form method='post' action='form_target.php'> <input type='text' name='fieldname' /> <button type='submit'/> </form> $('form').on('submit', function() { $.post( $(this).p

我有一个PHP网站,它有很多表单可以在提交时转到某些页面。所以它们看起来像这样:

<form method='post' action='form_target.php'>
    <input type='text' name='fieldname' />
    <button type='submit'/>
</form>
$('form').on('submit', function() {
  $.post(
    $(this).prop('action'), // Your url action
    $(this).serialize(),    // Your data
    success: function() {   // Your callback function
      alert('Submitted');
    }
  );
});

我想同样的事情也可以通过
$.post('form-target.php'),而不实际离开页面。但是我试图阻止为许多不同的表单编写JavaScript代码

那么,有没有一种简单的方法来检测页面上的表单,并将其转换为AJAX调用呢?可能通过绑定
onsubmit()
,或
onclick()事件到
$.post()呼叫

如有任何帮助,我们将不胜感激。


您可以这样做:

<form method='post' action='form_target.php'>
    <input type='text' name='fieldname' />
    <button type='submit'/>
</form>
$('form').on('submit', function() {
  $.post(
    $(this).prop('action'), // Your url action
    $(this).serialize(),    // Your data
    success: function() {   // Your callback function
      alert('Submitted');
    }
  );
});

您可以这样做:

<form method='post' action='form_target.php'>
    <input type='text' name='fieldname' />
    <button type='submit'/>
</form>
$('form').on('submit', function() {
  $.post(
    $(this).prop('action'), // Your url action
    $(this).serialize(),    // Your data
    success: function() {   // Your callback function
      alert('Submitted');
    }
  );
});
是的,你可以试试,这很简单

<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
    <script src="http://malsup.github.com/jquery.form.js"></script> 
    <script> 
        // wait for the DOM to be loaded 
        $(document).ready(function() { 
            // bind 'myForm' and provide a simple callback function 
            $('#myForm').ajaxForm(function() { 
                alert("Thank you for your submit!"); 
            }); 
        }); 
    </script> 
</head>
<body>
    <form id="myForm" method='post' action='form_target.php'>
       <input type='text' name='fieldname' />
       <button type='submit'/>
    </form>
</body>
</html>

//等待加载DOM
$(文档).ready(函数(){
//绑定“myForm”并提供一个简单的回调函数
$('#myForm').ajaxForm(函数(){
提醒(“感谢您的提交!”);
}); 
}); 
是的,您可以尝试,这非常简单易用

<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
    <script src="http://malsup.github.com/jquery.form.js"></script> 
    <script> 
        // wait for the DOM to be loaded 
        $(document).ready(function() { 
            // bind 'myForm' and provide a simple callback function 
            $('#myForm').ajaxForm(function() { 
                alert("Thank you for your submit!"); 
            }); 
        }); 
    </script> 
</head>
<body>
    <form id="myForm" method='post' action='form_target.php'>
       <input type='text' name='fieldname' />
       <button type='submit'/>
    </form>
</body>
</html>

//等待加载DOM
$(文档).ready(函数(){
//绑定“myForm”并提供一个简单的回调函数
$('#myForm').ajaxForm(函数(){
提醒(“感谢您的提交!”);
}); 
}); 

您可以将
.submit
事件附加到所有表单以捕获提交,然后在事件对象上使用
.preventDefault()
来阻止实际的页面提交(阻止它更改页面)。然后序列化表单的数据(创建一个名称-值配对字符串),从表单元素的action属性获取url,然后调用jquery的ajax函数

$(“表单”)
作为选择器的一部分而不使用任何其他内容,会将其附加到页面上的所有表单

HTML

为了进一步扩展它,您可以使它使每个表单执行一个特定的成功方法,这将有助于您在需要为特定表单提交执行特定操作的情况下

首先给每个表单一个data-*属性,我们可以在提交事件中使用该属性来触发该表单的特定函数

<form method='post' action='form_target.php' 
                    data-onerror="nameSubmitError" 
                    data-onsuccess="nameSubmitSuccess">
以及在.submit事件中

$("form").submit(function(e){
    e.preventDefault();
    var data = $(this).serialize();
    var url = $(this).attr("action");
    var errorCallback = $(this).data("onerror");
    var successCallback = $(this).data("onsuccess");
    $.ajax({
       url:url,
       type:"POST",
       success:function(){
          //Check that we have a defined function before trying to execute it
          if( typeof(window[successCallback]) == "function" ) {
             //We do have a defined function so execute it
             window[successCallback]();
          }
       },
       error:function() {
          //Check that we have a defined function before trying to execute it
          if( typeof(window[errorCallback]) == "function" ) {
             //We do have a defined function so execute it
             window[errorCallback]();
          }
       }
    });
});
当然,将所有回调函数放在全局空间会污染全局空间,因此您可以将所有函数设置到单个对象中,并使用对象名称,而不是
window

var formCallbacks = {
    nameSubmitError:function() {
      //Do some code that will handle the error
    },
    nameSubmitSuccess: function() {
      //Do some code that will handle the success
    }
};
在.submit event change
窗口中
表单回调

//window[errorCallback]();
//Becomes 
formCallbacks[errorCallback]();

您可以将
.submit
事件附加到所有表单以捕获提交,然后在事件对象上使用
.preventDefault()
来阻止实际的页面提交(阻止它更改页面)。然后序列化表单的数据(创建一个名称-值配对字符串),从表单元素的action属性获取url,然后调用jquery的ajax函数

$(“表单”)
作为选择器的一部分而不使用任何其他内容,会将其附加到页面上的所有表单

HTML

为了进一步扩展它,您可以使它使每个表单执行一个特定的成功方法,这将有助于您在需要为特定表单提交执行特定操作的情况下

首先给每个表单一个data-*属性,我们可以在提交事件中使用该属性来触发该表单的特定函数

<form method='post' action='form_target.php' 
                    data-onerror="nameSubmitError" 
                    data-onsuccess="nameSubmitSuccess">
以及在.submit事件中

$("form").submit(function(e){
    e.preventDefault();
    var data = $(this).serialize();
    var url = $(this).attr("action");
    var errorCallback = $(this).data("onerror");
    var successCallback = $(this).data("onsuccess");
    $.ajax({
       url:url,
       type:"POST",
       success:function(){
          //Check that we have a defined function before trying to execute it
          if( typeof(window[successCallback]) == "function" ) {
             //We do have a defined function so execute it
             window[successCallback]();
          }
       },
       error:function() {
          //Check that we have a defined function before trying to execute it
          if( typeof(window[errorCallback]) == "function" ) {
             //We do have a defined function so execute it
             window[errorCallback]();
          }
       }
    });
});
当然,将所有回调函数放在全局空间会污染全局空间,因此您可以将所有函数设置到单个对象中,并使用对象名称,而不是
window

var formCallbacks = {
    nameSubmitError:function() {
      //Do some code that will handle the error
    },
    nameSubmitSuccess: function() {
      //Do some code that will handle the success
    }
};
在.submit event change
窗口中
表单回调

//window[errorCallback]();
//Becomes 
formCallbacks[errorCallback]();

$('form')。onsubmit(…)
应该足够简单。@MarcB您的意思是.submit()或.on('submit'是的,您使用onsubmit的例子将是一个干净的方法。(当然,使用正确的jQuery方法绑定到submit事件)可能重复的
$('form')。onsubmit(…)
应该足够简单。@MarcB您的意思是.submit()或者.on('submit'是的,您认为使用onsubmit是一种干净的方法。(当然,使用正确的jQuery方法绑定到submit事件)@CengizFrostclaw可能重复,您当然可以用
表单
替换
#myForm
,以所有表单为目标。@CengizFrostclaw当然可以用
表单
替换
#myForm
以所有表单为目标。不要忘记
防止默认值
返回false
,以防止页面更改@PatrickEvans是的,我想问这个问题。什么是prop?我可以用
attr()
代替它吗?而且,它会将“form\u target”转换为“”?这会产生错误:未捕获语法错误:意外标记:不要忘记
preventDefault
returnfalse
,以防止页面changing@PatrickEvans是的,我想问这个问题。什么是prop?我可以用
attr()
来代替它吗?而且,它会将“form\u target”转换为“”这给出了一个错误:Uncaught SyntaxError:Unexpected token:wow,您最后是如何设置这些链接的样式的?
围绕链接我尝试了您的解决方案,(加载jquery后)console没有显示任何错误,但表单仍然通过转到页面提交。也没有调用成功和错误函数。这就像我根本没有添加脚本一样。我应该在表单之后编写此脚本吗?编辑:我将您的代码包装在
$document.ready(function(){});
中,现在它可以工作,但会出现错误。我将尝试修复它:)谢谢你的帮助!谢谢所有其他的答案。哦,我添加了