2008-12-17 106 views
80

的回应,我有以下代码:如何捕捉form.submit

<script type="text/javascript"> 
     function SubmitForm() 
     { 

      form1.submit(); 
     } 

     function ShowResponse() 
     { 

     } 
</script> 
. 
. 
. 
<div> 
    <a href="#" onclick="SubmitForm();">Click</a> 
</div> 

我想捕捉的form1.submit HTML响应?我该怎么做呢?我可以注册任何回调函数form1.submit方法吗?

回答

87

使用普通的javascript无法轻松完成此操作。发布表单时,表单输入会发送到服务器,并刷新页面 - 数据在服务器端进行处理。也就是说,submit()函数实际上并不返回任何内容,它只是将表单数据发送到服务器。

如果你真的想获得在JavaScript中响应(不含页刷新),那么你就需要使用AJAX,当你开始谈论使用AJAX,你会需要使用图书馆。 jQuery是迄今为止最受欢迎的,也是我个人最喜欢的。有一个名为Form的jQuery插件,它可以完成听起来像你想要的。

这里是你如何使用jQuery和插件:

$('#myForm') 
    .ajaxForm({ 
     url : 'myscript.php', // or whatever 
     dataType : 'json', 
     success : function (response) { 
      alert("The server says: " + response); 
     } 
    }) 
; 
+4

jQuery表单插件+1。这很棒,但你的'target'属性错了。它不像表单的'action'属性;即它不是提交目的地。从[docs](http://malsup.com/jquery/form/#options-object):** target - 标识要使用服务器响应更新的页面中的元素。** – JCotton 2011-08-10 23:41:50

+0

@JCotton ,谢谢 - 编辑! – nickf 2011-08-11 09:02:40

+13

要公平,您不需要为AJAX使用库。库是使用JavaScript编写的,因此存在非库解决方案。那就是说,我100%赞成使用一个库来抽象所有涉及进行AJAX调用的荒谬和复杂性。 – Jason 2013-09-11 21:36:37

0

您需要使用AJAX。提交表单通常会导致浏览器加载新页面。

7

我不知道,你明白什么提交()不...

当你做form1.submit();形式的信息发送到Web服务器。

WebServer将做任何它应该做的事情,并返回一个全新的网页到客户端(通常是改变了某些东西的同一页面)。

因此,您无法“捕捉”form.submit()动作的返回。

+0

我创建了另一个html页面,返回此作为回应。 – Khushboo 2016-08-12 08:34:45

4

没有回调。这就像跟随一个链接。

如果要捕获服务器响应,请使用AJAX或将其发布到Iframe,并抓住iframe的onload()事件之后出现的内容。

0

你可以使用javascript和AJAX技术来做到这一点。看看jQuery,并在form plug in。你只需要包含两个js文件来为form.submit注册一个回调。

46

一个AJAX方法是设置一个无形的作为表单的目标,并在其onload处理程序读取的内容。但是为什么还有Ajax呢?

注:我只是想提这个选择,因为一些问题的答案声称,这是不可能实现这一目标没有Ajax。

1

如果你想捕捉使用Chrome,你可以遵循这些简单的步骤一个AJAX请求的输出:

  1. 开拓程序员工具箱
  2. 转至控制台和里面任何一处
  3. 在出现的菜单中,点击“Enable XMXHTTPRequest Logging”
  4. 这样做后,每当你发出一个AJAX请求时,一个以“XHR完成加载:http:// ......”开始的消息将出现在你的控制台。
  5. 点击出现的链接,将会出现“资源标签”,您可以在其中看到标题和回复的内容!
20

我正在这样做,它的工作。

$('#form').submit(function(){ 
    $.ajax({ 
     url: $('#form').attr('action'), 
     type: 'POST', 
     data : $('#form').serialize(), 
     success: function(){ 
     console.log('form submitted.'); 
     } 
    }); 
    return false; 
}); 
0

您可以event.preventDefault()单击处理程序为您的提交按钮,以确保HTML表单默认submit不会触发事件(这是什么导致了页面刷新)。

另一种选择是使用hackier表单标记:这是<form>type="submit"的使用,它妨碍了期望的行为;因为这最终会导致点击事件刷新页面。

如果你想仍然使用<form>,你不想编写自定义单击处理程序,您可以通过暴露承诺方法successerror等使用jQuery的ajax方法,它抽象了整个问题离开你


总括来说,你可以通过解决您的问题:

•使用event.preventDefault()

防止在处理函数的默认行为3210

•使用不具有默认行为的元素(例如<form>

•使用jQuery ajax


(我只注意到这个问题是从2008年,不知道为什么它在我的饲料出现了,无论如何,希望这是一个明确的答案)

-4

你可以做到没有ajax。

在下面写下你的喜欢。

.. .. ..

,然后在 “action.php的”

然后frmLogin.submit后();

读取变量$ submit_return ..

$ submit_return包含返回值。

祝你好运。

0

你可以做到这一点使用jQueryajax()方法:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<script language="javascript" type="text/javascript"> 
 
function submitform() { 
 
     $.ajax({ 
 
     headers: { 
 
      'Accept': 'application/json', 
 
      'Content-Type': 'application/json' 
 
     }, 
 
     type: "POST", 
 
     url : "/hello.hello", 
 
     dataType : "json", 
 
     data : JSON.stringify({"hello_name": "hello"}), 
 
     error: function() { 
 
      alert('loading Ajax failure'); 
 
     }, 
 
    \t onFailure: function() { 
 
      alert('Ajax Failure'); 
 
    \t }, 
 
    \t statusCode: { 
 
      404: function() { 
 
      alert("missing info"); 
 
      } 
 
    \t }, 
 
     success : function (response) { 
 
      alert("The server says: " + JSON.stringify(response)); 
 
     } 
 
     }) 
 
     .done(function(data) { 
 
     $("#result").text(data['hello']); 
 
     }); 
 
};</script>

1
$.ajax({ 
     url: "https://stackoverflow.com/users/login/", //give your url here 
     type: 'POST', 
     dataType: "json", 
     data: logindata, 
     success: function (data){ 
     // alert(data); do your stuff 
     }, 
     error: function (data){ 
     // alert(data); do your stuff 
     } 
    }); 
2

这是我对这个问题的代码:

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

<script type='text/javascript'> 
/* 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()}); 

    /* Alerts the results */ 
    posting.done(function(data) { 
    alert('success'); 
    }); 
}); 
</script> 
1

大厦答案由@rajesh_kw (https://stackoverflow.com/a/22567796/4946681),我处理表单POST错误和成功:

$('#formName').on('submit', function(event) { 
     event.preventDefault(); // or return false, your choice 
     $.ajax({ 
      url: $(this).attr('action'), 
      type: 'post', 
      data: $(this).serialize(), 
      success: function(data, textStatus, jqXHR) { 
       // if success, HTML response is expected, so replace current 
       if(textStatus === 'success') { 
        // https://stackoverflow.com/a/1236378/4946681 
        var newDoc = document.open('text/html', 'replace'); 
        newDoc.write(data); 
        newDoc.close(); 
       } 
      } 
     }).fail(function(jqXHR, textStatus, errorThrown) { 
      if(jqXHR.status == 0 || jqXHR == 302) { 
       alert('Your session has ended due to inactivity after 10 minutes.\nPlease refresh this page, or close this window and log back in to system.'); 
      } else { 
       alert('Unknown error returned while saving' + (typeof errorThrown == 'string' && errorThrown.trim().length > 0 ? ':\n' + errorThrown : '')); 
      } 
     }); 
    }); 

我利用this让我的逻辑是可重用的,我希望HTML就成功了,所以我使其和替换当前页面返回,在我的情况下,如果会话超时,我希望重定向到登录页面,因此我拦截该重定向以保留页面状态。

现在,用户可以通过另一个选项卡登录并尝试他们再次提交。

0
$(document).ready(function() { 
    $('form').submit(function(event) { 
     event.preventDefault(); 
     $.ajax({ 
      url : "<wiki:action path='/your struts action'/>",//path of url where u want to submit form 
      type : "POST", 
      data : $(this).serialize(), 
      success : function(data) { 
       var treeMenuFrame = parent.frames['wikiMenu']; 
       if (treeMenuFrame) { 
        treeMenuFrame.location.href = treeMenuFrame.location.href; 
       } 
       var contentFrame = parent.frames['wikiContent']; 
       contentFrame.document.open(); 
       contentFrame.document.write(data); 
       contentFrame.document.close(); 
      } 
     }); 
    }); 
}); 

大段引用

都使用$(文件)。就绪的firrst(函数())这种使用( 'formid')内。提交(函数(事件) ) ,然后防止默认操作调用ajax表单提交 $ .ajax({,,,,}); 将采取参U,可根据您的要求 选择然后调用机能缺失的成功:功能(数据){// 做任何你想要我的例子穿上DIV响应HTML}

0

首先我们需要serializeObject的( );

$.fn.serializeObject = function() { 
    var o = {}; 
    var a = this.serializeArray(); 
    $.each(a, function() { 
     if (o[this.name]) { 
      if (!o[this.name].push) { 
       o[this.name] = [o[this.name]]; 
      } 
      o[this.name].push(this.value || ''); 
     } else { 
      o[this.name] = this.value || ''; 
     } 
    }); 
    return o; 
}; 

那么你犯了一个基本的岗位,并得到响应

$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) { 
if(data){ 
//do true 
} 
else 
{ 
//do false 
} 

}); 
0

我有以下代码使用Ajax和多部分表单数据perfactly运行

function getUserDetail() 
{ 
    var firstName = document.getElementById("firstName").value; 
    var lastName = document.getElementById("lastName").value; 
    var username = document.getElementById("username").value; 
    var email = document.getElementById("email").value; 
    var phoneNumber = document.getElementById("phoneNumber").value; 
    var gender =$("#userForm input[type='radio']:checked").val(); 
    //var gender2 = document.getElementById("gender2").value; 
    //alert("fn"+firstName+lastName+username+email); 
    var roleIndex = document.getElementById("role"); 
    var role = roleIndex.options[roleIndex.selectedIndex].value; 
    var jobTitleIndex = document.getElementById("jobTitle"); 
    var jobTitle = jobTitleIndex.options[jobTitleIndex.selectedIndex].value; 
    var shiftIdIndex = document.getElementById("shiftId"); 
    var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value; 


    var addressLine1 = document.getElementById("addressLine1").value; 
    var addressLine2 = document.getElementById("addressLine2").value; 
    var streetRoad = document.getElementById("streetRoad").value; 

    var countryIndex = document.getElementById("country"); 
    var country = countryIndex.options[countryIndex.selectedIndex].value; 

    var stateIndex = document.getElementById("state"); 
    var state = stateIndex.options[stateIndex.selectedIndex].value; 

    var cityIndex = document.getElementById("city"); 
    var city = cityIndex.options[cityIndex.selectedIndex].value; 



    var pincode = document.getElementById("pincode").value; 

    var branchIndex = document.getElementById("branch"); 
    var branch = branchIndex.options[branchIndex.selectedIndex].value; 

    var language = document.getElementById("language").value; 
    var profilePicture = document.getElementById("profilePicture").value; 
    //alert(profilePicture); 
    var addDocument = document.getElementById("addDocument").value; 


    var shiftIdIndex = document.getElementById("shiftId"); 
    var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value; 


    var data = new FormData(); 
    data.append('firstName', firstName); 
    data.append('lastName', lastName); 
    data.append('username', username); 
    data.append('email', email); 
    data.append('phoneNumber', phoneNumber); 
    data.append('role', role); 
    data.append('jobTitle', jobTitle); 
    data.append('gender', gender); 
    data.append('shiftId', shiftId); 
    data.append('lastName', lastName); 
    data.append('addressLine1', addressLine1); 
    data.append('addressLine2', addressLine2); 
    data.append('streetRoad', streetRoad); 
    data.append('country', country); 
    data.append('state', state); 
    data.append('city', city); 
    data.append('pincode', pincode); 
    data.append('branch', branch); 
    data.append('language', language); 
    data.append('profilePicture', $('#profilePicture')[0].files[0]); 
    for (var i = 0; i < $('#document')[0].files.length; i++) { 
      data.append('document[]', $('#document')[0].files[i]); 
     } 



    $.ajax({ 
     //url : '${pageContext.request.contextPath}/user/save-user', 
     type: "POST", 
     Accept: "application/json", 
     async: true, 
     contentType:false, 
     processData: false, 
     data: data, 
     cache: false, 

     success : function(data) {  
      reset(); 
      $(".alert alert-success alert-div").text("New User Created Successfully!"); 
     }, 
     error :function(data, textStatus, xhr){ 
      $(".alert alert-danger alert-div").text("new User Not Create!"); 
     } 


    }); 


// 

} 
0

您可以使用jQuery.post()和回报服务器结构良好的JSON答案。它还允许您直接在服务器上验证/清理数据,这是一种很好的做法,因为它比客户端更安全(甚至更容易)。

例如,如果您需要发布HTML表单服务器(以saveprofilechanges.php)与简单的注册用户数据:

一客户端部分:

.A。HTML部分:

<form id="user_profile_form"> 
    <label for="first_name"><input type="text" name="first_name" id="first_name" required />First name</label> 
    <label for="family_name"><input type="text" name="family_name" id="family_name" required />Family name</label> 
    <label for="email"><input type="email" name="email" id="email" required />Email</label> 
    <input type="submit" value="Save changes" id="submit" /> 
</form> 

I.b.剧本部分:

$(function() { 
    $("#user_profile_form").submit(function(event) { 
     event.preventDefault(); 
     var postData = { 
     first_name: $('#first_name').val(), 
     family_name: $('#family_name').val(), 
     email: $('#email').val() 
     }; 
     $.post("/saveprofilechanges.php", postData, 
     function(data) { 
      var json = jQuery.parseJSON(data); 
      if (json.ExceptionMessage != undefined) { 
      alert(json.ExceptionMessage); // the exception from the server 
      $('#' + json.Field).focus(); // focus the specific field to fill in 
      } 
      if (json.SuccessMessage != undefined) { 
      alert(json.SuccessMessage); // the success message from server 
      } 
     }); 
    }); 
}); 

二,服务器部分(saveprofilechanges.php):

$data = $_POST; 
if (!empty($data) && is_array($data)) { 
    // Some data validation: 
    if (empty($data['first_name']) || !preg_match("/^[a-zA-Z]*$/", $data['first_name'])) { 
     echo json_encode(array(
     'ExceptionMessage' => "First name missing or incorrect (only letters and spaces allowed).", 
     'Field' => 'first_name' // Form field to focus in client form 
     )); 
     return FALSE; 
    } 
    if (empty($data['family_name']) || !preg_match("/^[a-zA-Z ]*$/", $data['family_name'])) { 
     echo json_encode(array(
     'ExceptionMessage' => "Family name missing or incorrect (only letters and spaces allowed).", 
     'Field' => 'family_name' // Form field to focus in client form 
     )); 
     return FALSE; 
    } 
    if (empty($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) { 
     echo json_encode(array(
     'ExceptionMessage' => "Email missing or incorrectly formatted. Please enter it again.", 
     'Field' => 'email' // Form field to focus in client form 
     )); 
     return FALSE; 
    } 
    // more actions.. 
    // more actions.. 
    try { 
     // Some save to database or other action..: 
     $this->User->update($data, array('username=?' => $username)); 
     echo json_encode(array(
     'SuccessMessage' => "Data saved!" 
     )); 
     return TRUE; 
    } catch (Exception $e) { 
     echo json_encode(array(
     'ExceptionMessage' => $e->getMessage() 
     )); 
     return FALSE; 
    } 
} 
1

非jQuery的方式,从12me21的评论:

var xhr = new XMLHttpRequest(); 
xhr.open("POST", "/your/url/name.php"); 
xhr.onload = function(event){ 
    alert("The server says: " + event.target.response); 
}; 
var formData = new FormData(document.getElementById("myForm")); 
xhr.send(formData);