This article mainly introduces the method of asynchronously submitting form data in jquery ajax for everyone. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
Use the ajax method of jquery to submit the form asynchronously. After success, the json data is returned in the background and processed by the callback function. You do not need to refresh the page to achieve asynchronous purposes;
You can use serialize to process the form data. () method for serialization, and if the submitted data includes a file stream, you need to use the FormData object:
Use form data without a file: var data = $(form).serialize();
Use form data with files: var data = new FormData($(form)[0]);
1. Ajax submission data without files:
html:form form
<form id="addForm" action="${pageContext.request.contextPath}/admin/saveAdd" method="post"> <input type="text" name="name" placeholder="请输入名字" /> <input type="password" name="password" placeholder="密码"/> </form> <button type="button" id="submitAdd">确认</button>
jquery asynchronous processing
##
$("#submitAdd").click(function(){ var targetUrl = $("#addForm").attr("action"); var data = $("#addForm").serialize(); $.ajax({ type:'post', url:targetUrl, cache: false, data:data, dataType:'json', success:function(data){ alert('success'); }, error:function(){ alert("请求失败") } }) })
2. Ajax submission of data with files:
html: form form Form forms with file uploads need to add enctype="multipart" to the