如何捕获form.submit的响应

我有以下代码:

<script type="text/javascript"> function SubmitForm() { form1.submit(); } function ShowResponse() { } </script> . . . <div> <a href="#" onclick="SubmitForm();">Click</a> </div> 

我想捕获form1.submit的html响应? 我该怎么做呢? 我可以注册任何callback函数form1.submit方法?

用简单的JavaScript你将无法轻松做到这一点。 发布表单时,表单input将发送到服务器,并刷新页面 – 数据在服务器端处理。 也就是说, submit()函数实际上并不返回任何东西,它只是将表单数据发送到服务器。

如果你真的想在Javascript中得到响应(没有页面刷新),那么你需要使用AJAX,当你开始谈论使用AJAX时,你需要使用一个库。 jQuery是迄今为止最受欢迎的,也是我个人最喜欢的。 jQuery的一个很棒的插件叫做Form ,它可以完成你想要的东西。

以下是您将如何使用jQuery和该插件:

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

一个Ajax替代方法是将一个不可见的<iframe>为您的表单目标,并在其onload处理函数中读取该<iframe>的内容。 但为什么还有Ajax呢?

注:我只是想提到这个select,因为一些答案声称,没有Ajax是不可能的

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

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

我不确定你了解submit()是做什么的

当你做form1.submit(); 表单信息被发送到networking服务器。

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

所以,你无法“捕捉”form.submit()动作的返回。

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

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

如果您想要使用Chrome浏览器捕获AJAX请求的输出,您可以按照以下简单的步骤进行操作:

  1. 打开程序员工具箱
  2. 转到控制台,并在其中的任何地方
  3. 在出现的菜单中,点击“启用XMXHTTPRequestlogging”
  4. 这样做后,每次你做一个AJAX请求消息开始“XHR完成加载:http:// ……”将出现在您的控制台。
  5. 点击出现的链接,将会出现“资源标签”,您可以在其中看到标题和回复的内容!
  $.ajax({ url: "/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 } }); 

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

 <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> 

build立在@rajesh_kw( https://stackoverflow.com/a/22567796/4946681 )的答案上,我处理表单错误和成功:

  $('#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成功返回,所以我渲染并replace当前页面,在我的情况下,我希望redirect到login页面,如果会话超时,所以我拦截了redirect,以保持页面的状态。

现在用户可以通过另一个选项卡login并再次尝试提交。

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

你可以使用JavaScript和AJAX技术来做到这一点。 看看jQuery,并在这种forms插件 。 你只需要包含两个js文件来为form.submit注册一个callback。

您可以在提交button的点击处理程序中使用event.preventDefault() ,以确保HTML表单默认submit事件不会触发(这是导致页面刷新的原因)。

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

如果你仍然想使用<form> ,并且你不想编写自定义的点击处理程序,那么可以使用jQuery的ajax方法,它通过暴露successerror等承诺方法来为你抽象整个问题。


回顾一下,你可以通过以下方式解决你的问题:

•通过使用event.preventDefault()来防止处理函数中的默认行为

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

•使用jQuery ajax


(我刚刚注意到这个问题是从2008年开始的,不知道为什么它出现在我的Feed中;无论如何,希望这是一个明确的答案)

你可以用jQuery和ajax()方法完成这个工作:

 <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'); }, onFailure: function () { alert('Ajax Failure'); }, statusCode: { 404: function() { alert("missing info"); } }, success : function (response) { alert("The server says: " + JSON.stringify(response)); } }) .done(function( data ) { $("#result").text(data['hello']); }); };</script> 
  $(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(); } }); }); }); 

大段引用

('formid')。submit(function(event)),然后防止调用ajax表单提交的默认操作$ .ajax({,, ,}); 它会采取参数ü可以根据您的要求select然后调用函数成功:函数(数据){/ /做任何你想我的例子把响应的HTML在div}

首先我们需要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 } }); 

我有以下代码完全运行使用ajax与多部分forms的数据

 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!"); } }); // } 

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

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

I.客户部分:

Ia 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> 

Ib脚本部分:

 $(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 } }); }); }); 

II。 服务器部分(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; } } 

你可以做到没有Ajax。

在下面写下你的喜好。

.. ..

然后在“action.php”

然后frmLogin.submit();

读取variables$ submit_return ..

$ submit_return包含返回值。

祝你好运。