Jquery’s $.ajax method can implement ajax calls and set url, post, parameters, etc.
If you need to write a lot of code to submit an existing Form, why not just transfer the submission of the Form directly to ajax.
The previous processing method
For example, the Form code is as follows
When submitted, it will jump to the action.aspx page. And the value can be obtained through Request.Params["name"].
Thinking
If you don’t want to refresh the page and use ajax, you have to specify the url and other information in $.ajax, which is difficult to maintain.
I checked online and found that foreigners had a solution a long time ago. Use ajax to submit directly according to the Form information. Does not refresh the page.
Reference: http://jquery.malsup.com/form/
It’s very useful, but I would still like to write one for myself.
Core JS code
//将form转为AJAX提交 function ajaxSubmit(frm, fn) { var dataPara = getFormJson(frm); $.ajax({ url: frm.action, type: frm.method, data: dataPara, success: fn }); } //将form中的值转换为键值对。 function getFormJson(frm) { var o = {}; var a = $(frm).serializeArray(); $.each(a, function () { if (o[this.name] !== undefined) { 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; }
The first parameter of the ajaxSubmit method is the form to be submitted, and the second parameter is the processing function after the ajax call is successful.
Pass the form action to the ajax url, the form method to the ajax type, and then pass the formatted form content to data.
The getFormJson method converts form elements into json format key-value pairs. In the form: {name:'aaa',password:'tttt'}, be careful to put the ones with the same name in an array.
Call
//调用$(document).ready(function(){ $('#Form1').bind('submit', function(){ ajaxSubmit(this, function(data){ alert(data); }); return false; }); });
Before calling the ajaxSubmit method, you can verify whether the data is correct. You can add your own call return post-processing code at alert(data).
After calling the ajaxSubmit method, you must add a return false; statement to prevent the Form from actually being submitted
For more Jquery Ajax custom submission form Form no refresh related articles, please pay attention to the PHP Chinese website!