添加拖曳事件

adding tow events

本文关键字:事件 添加      更新时间:2023-09-26

我有一个表单,它将一些数据发送到一个php文件,然后返回一些结果作为示例:

<form action"<?php $_SERVER['PHP_SELF']?>" method="post" id="data">
  <input type"text" name="first_name"/>
  <input type="text" name="last_name"/>
</form>

然后在 JavaScript 中,我想以提交形式捕获 clcik 事件作为示例:

$("#data").submit(function(){
some code .....
});

这将阻止将输入表单提交到php文件的默认操作,问题是我可以发送PHP文件的表单数据以及同一表单的同一时间捕获事件吗?

注意从 php 文件返回的数据将被另一个 php 需要 功能

为了防止表单提交的默认行为(即页面重新加载),您需要使用这样的event.preventDefault()

$("#data").submit(function(event){
    event.preventDefault();
    //some code .....
});

要在不刷新页面的情况下将表单数据发布到php中,您需要使用任何 jQuery 可用的ajax方法,例如 .post()(它将使用HTTP POST方法发送表单值)如

$("#data").submit(function(event){
    event.preventDefault();// prevent page reload
    // Now post the form using Ajax
    // $(this).serialize() will return an array of all form fields as
    //                                                 name value pair 
    $.post('some_script.php',$(this).serialize(),function(data){
        // Just to check if everything is working well
        console.log('Form Submitted Successfully.');
        // do whatever you want with the data
   });
});

如果您的 php 脚本以json格式返回数据,您可以使用 php 设置content-Type标头,或者通过在第 4 个参数中将dataType指定为JSON来强制 jQuery 将返回数据视为JSON,例如

   $.post('some_script.php',$(this).serialize(),function(data){
        // Just to check if everything is working well
        console.log('Form Submitted Successfully.');
        // do whatever you want with the data
   },'json');
$("#data").submit(function(e){
e.preventDefault();
$.post("<?php echo $_SERVER['PHP_SELF'] ?>",$(this).serialize(),function(r){ //Do Some Action });
});