en

designoir

request

request.js

/**
 * function request
 * Copyright (C) 2006-2007 Dao Gottwald
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact information:
 *   Dao Gottwald <dao at design-noir.de>
 *
 * @version 1.5
 * @url	    http://design-noir.de/webdev/JS/request/
 */

/*@cc_on @if (@_win32 && @_jscript_version >= 5) if (!window.XMLHttpRequest)
window.XMLHttpRequest = function() { return new ActiveXObject("Microsoft.XMLHTTP") }
@end @*/

function request(url, method, data, callback) {
	var http = new XMLHttpRequest;
	if (!http)
		return false;
	var _data;
	if (data != null && typeof data == "object") {
		_data = [];
		for (var i in data)
			_data.push(i + "=" + encodeURIComponent(data[i]));
		_data = _data.join("&");
	} else {
		_data = data;
	}
	method = method.toUpperCase();
	if (method == "POST") {
		http.open(method, url, true);
		http.setRequestHeader("Method", "POST "+url+" HTTP/1.1");
		http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	} else {
		if (_data)
			url += (url.indexOf("?") == -1 ? "?" : "&") + _data;
		_data = "";
		http.open(method, url, true);
	}
	if (callback)
		http.onreadystatechange = function() {
			if (http.readyState == 4) {
				http.onreadystatechange = function(){};
				callback(http);
			}
		};
	http.send(_data);
	return http;
}

Beispiel #1: testScript.js

function receiveIt (http) {
	if (http.status == 200)
		alert (http.responseText);
	else
		alert ('Request failed.');
}

if (!request ('whatever.php', 'POST', 'foo=bar&baz=qux', receiveIt))
	alert ('Request failed.');

request ('whatever.php', 'GET', {foo:'bar?',baz:'yet to encode'}, receiveIt);

Kommentare

  1. YaroslaF meinte am 13. April ’07, 15:46 Uhr ():
    Thanks for your code. I had trouble with IE 6.0 and windows-1250 charset. In any other browser everything was OK.

    encodeURIComponent() was the key, encode() still was not enough.

HTML wird nicht interpretiert.

Geändert am 25. Juli ’06 Dão G., 2005–2010
aggressiv akt andromeda bar beine blue efeu frontal fugaetu industriell komet land noir rost rot sonnenblume splash split winter wolke zeit