简体   繁体   English

使用Ajax手动提交表单

[英]Submitting the form manually using Ajax

I am trying to call a servlet on form submit using ajax. 我正在尝试使用ajax在表单提交上调用servlet。 But it's not hitting the ajax and page reloads. 但这并没有达到ajax和页面重新加载的目的。 I am triggering form submit manually and after that on that submit function i am calling the ajax method. 我手动触发表单提交,然后在该提交功能上调用ajax方法。

 $("#image1").on('change', function(event) { $('#myform').trigger('submit'); alert("button clicked"); // this is submitted $("#myform").submit(function(e) { // this is not happening event.preventDefault(); alert('form clicked'); //var formId=("#myform").submit(); $.ajax({ type: 'GET', // GET or POST or PUT or DELETE // verb url: "/bin/mr/controller?q=iechange", data: $("#myform").serialize(), // type // sent // to // server dataType: 'json', // Expected data format from // server processdata: true, // True or False success: function(data) { // On Successfull alert('call success'); console.log(data); }, error: function(msg) { // When Service call alert('call fail'); // fails } }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="myform" > <input name="img" id="image1" type="file" accept="image/*"> </form> 

You need to bind your submit event handler when the page loads. 页面加载时,您需要绑定您的submit事件处理程序。

Currently you are trying to bind it after you have manually triggered the submission… which is too late because the event will have been and gone by then. 当前,您正在尝试手动触发提交后绑定它……这太晚了,因为该事件已经过去了。

Move the code which binds the submit event outside the event handler for the change event. 将绑定了submit事件的代码移到change事件的事件处理程序之外

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM