Home > Article > Web Front-end > jquery+ajax implements asynchronous submission of form data
This time I will bring you jquery Ajax implements asynchronous submission of form data, jquery ajax implements asynchronous submission of form data. What are the precautions ? The following is a practical case. Let’s take a look.
Use jquery's ajax method to submit the form asynchronously. After success, the json data will be returned in the background, Callback functionprocessing, you can achieve asynchronous purposes without refreshing the page;
The data processed in the form can be serialized using the serialize() method. If the submitted data includes a file stream, you need to use the FormData object:
Use form data without files: var data = $(form).serialize();
Use form data with files: var data = new FormData($(form)[0]);
1. Ajax submission data without files:
html: 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 data with files:
html:form form
For forms with file upload, you need to add the enctype="multipart/form-data" attribute to the