使用ajax方式傳送表單資料

 Wed, 05 Jul 2006 17:36:41 +0800

不論在IE利用msxml2裡面的xmlhttp物件或是在Mozilla裡面利用XMLHttpRequest物件,都可以使用http的POST方法來向伺服器提出請求。

寫一個簡單的javascript來測試一下。只是看看ajax到底怎麼操作,所以並沒有做多餘的功能。

程式如下:

function xmlhttp() 
{
try{return new ActiveXObject("Msxml2.XMLHTTP");} catch(e){}
try{return new ActiveXObject("Microsoft.XMLHTTP");} catch(e){}
try{return new XMLHttpRequest();} catch(e){}
alert("XMLHttpRequest Object not existed!!");
return null;
}
var debug = 0;
function fwXMLHttpForm (_host) {
// Public Properties
this.xmlhttp = new xmlhttp();
this.result = "";
// Private Methods
this._createBoundary = function () {
var tmp = Math.random();
var thisDate = new Date();
tmp = Math.abs(tmp*thisDate.getTime());
tmp = "--------" + tmp + "--------";
return tmp;
}
this._createField = function (_field, _value) {
var tmp = "--" + this._boundary + this.CRLF;
tmp += "Content-Disposition: form-data; name="" + _field + """ + this.CRLF;
tmp += "Content-Transfer-Encoding: binary" + this.CRLF + this.CRLF;
tmp += _value + this.CRLF
tmp += "--" + this._boundary + "--" + this.CRLF + this.CRLF;
return tmp;
}
var formObj = this;
this.xmlhttp.onreadystatechange = function () {
if (formObj.xmlhttp.readyState == 4) {
if (formObj.xmlhttp.status == 200) {
formObj.result = formObj.xmlhttp.responseText;
}
else {
formObj.errCode = formObj.xmlhttp.status;
formObj.result = formObj.xmlhttp.responseText;
alert("Error in request!! HTTP RESPONSE STATUS: " + formObj.errCode);
}
}
}
// Private Properties
this._boundary = this._createBoundary();
this._host = _host;
this._fields = new Array();
this.CRLF = "rn";
// Public Methods
this.addField = function (_field, _value) {
this._fields.push(new Array(_field, _value));
}
this.removeField = function (_field) {
for (var i=0; i<this._fields.length; i++) {
var tmp = this._fields[i];
if (tmp[0] == _field) {
this._fields.splice(i,1);
}
}
}
this.emptyField = function () {
this._fields = new Array();
}
this.send = function () {
this.xmlhttp.open("POST", this._host);
var msgBody = "";
for (var i=0; i<this._fields.length; i++){
var tmp = this._fields[i];
msgBody += this._createField(tmp[0], tmp[1]);
}
this.xmlhttp.setRequestHeader("Content-Type","multipart/form-data; boundary="+this._boundary);
this.xmlhttp.setRequestHeader("Connection","Keep-Alive");
this.xmlhttp.setRequestHeader("Content-Length",msgBody.length);
this.xmlhttp.send(msgBody);
}
}

使用方法: