Examples of AJAX submitted form data analysis and ajax form instance analysis
This document describes how to submit form data through AJAX. Share it with you for your reference. The details are as follows:
Var TINY ={}; TINY. ajax = function () {return {/*** @ param string type: Request type, post, and get (currently only these two types are implemented) * @ param strng url request address * @ param object data Request Parameters when post is used, ex: data => {name: 'Adam '} * @ param function the callback function when callback is returned successfully */call: function (type, url, data, callback) {var xhr = window. XMLHttpRequest? New XMLHttpRequest: new ActiveXObject ('Microsoft. XMLHTTP '); // for ie xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {callback. call (this, xhr. responseText) ;}} switch (type. toUpperCase () {case 'post': xhr. open ('post', url, true); // This sentence is important. setRequestHeader ('content-type', 'application/x-www-form-urlencoded'); var formData = ''; for (var I in data) {formData + = I + '=' + data [I] + '&';} xhr. send (formData); break; default: xhr. open ('get', url, true); xhr. send (null) break ;}}}}();
Traverse the elements of the form and organize the parameter values into JSON format.
Here, the CheckBox check box is specially processed. the value received by the background is the value of all check box values separated by commas (,).
function serialForm(form){ var e = form.elements; var ht = new Array(); var checkbox = new Array(); for(var i = 0; i < e.length; i++) { if(e[i].type=="checkbox"){ if(e[i].checked){ if(checkbox[e[i].name] != null) checkbox[e[i].name].push(e[i].value); else checkbox[e[i].name] = [e[i].value]; } } else { ht.push(e[i].name+":'"+e[i].value+"'"); ht.push(","); } } for (var ddd in checkbox ){ ht.push(ddd + ":'" + checkbox[ddd] + "'"); ht.push(","); } ht.push("nt:0"); return eval('({' + ht.join("") + '})'); };
AJAX call:
TINY.ajax.call('post', 'listfrom.do', serialForm(frm), function(data){ var ret = eval('('+data+')'); if(ret.errid==0){ alert(ret.text); window.location.reload(); } else{ alert(ret.text); } });
When talking about the JSON format data returned by the server, the following formats are supported:
String str = "[{\"mailAddr\":\"edison@163.com\"}, {\"mailAddr\":\"jay@263.com\"}]";response.setContentType("application/json;charset=UTF-8");response.getWriter().write(str);
Frontend call
function show(){ $.post("listmail.do", {"name" : "John"}, function(data){ for(var i = 0; i < data.length; i++){ alert(data[i].mailAddr); } }, "json");}
I hope this article will help you with Ajax programming.