The example in this article describes how Ajax submits form data. Share to everyone for your reference. as follows:
var tiny={};
Tiny.ajax = function () {return {/** * @param string type request type, Post,get (currently only implemented) * @param strng URL requested address
* @param object data when the request parameter,ex:data=> {name: ' Adam '} * @param function callback When the POST request is used * * Call:function (type, URL, data, callback) {var xhr = window. XMLHttpRequest? New xmlhttprequest:new ActiveXObject (' microsoft.xmlhttp ');//for IE Xhr.onreadystatechange = function () {if (x
Hr.readystate = = 4 && xhr.status = Callback.call (this, xhr.responsetext);
Switch (Type.touppercase ()) {case ' post ': Xhr.open (' post ', url, true);
This sentence is more important xhr.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;
}
}
}
}();
Iterate through the elements of the form and organize the parameter values into JSON format
Here the CheckBox checkbox is specially processed, and the value received in the background is a comma concatenation of all check box values.
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 ("") + '} ');
Invocation of Ajax:
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);
}
);
Referring to the JSON-formatted data returned by the server side, support the following format
String str = "[{\" mailaddr\ ": \" Edison@163.com\ "}, {\" mailaddr\ ": \" Jay@263.com\ "}]";
Response.setcontenttype ("Application/json;charset=utf-8");
Response.getwriter (). write (str);
Front-End 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 your AJAX programming.