Ajax/xmlHttpRequest als object zonder jQuery

Een xmlHttpRequest, beter bekend als AJAX. Dit lijkt op de jQuery versie uiteraard alleen kan deze het zonder jQuery.
Het laat je zien hoe je zelf een request kan maken via standaard javascript.

Houd er rekening mee dat als je met XHR werkt dat je tegen het cross domain policy aan kan lopen. Dit houdt in dat je gewoon
niet bij de content mag als je iets opvraagt van een ander domein. Een oplossing hiervoor (ook hier ingebouwd) is om dit middels php dan op te halen.

function Ajax(params)
	{
		this.requestType = 'GET';
		this.xmlhttp = null;
		this.params = params;
		this.success = false;
		this.timer = false;
		this.aborted = false;

		if (window.XMLHttpRequest)
		{
			// for not so crappy browser
			this.xmlhttp = new XMLHttpRequest();
		} else {
			// ie5, 6, crap browser support
			this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}

		if (typeof params.requestType != 'undefined')
		{
			// make them uppercase so we dont have to jiggle around with user input
			this.requestType = this.params.requestType.toUpperCase();
		}

		// bind the constructor of the class to the xmlhttp object
		this.xmlhttp.Constructor = this;

		this.xmlhttp.onreadystatechange = function()
		{
			switch (this.readyState)
			{
				case 4:
					this.Constructor.success = true;
					if (this.status == 200)
					{
						if (typeof this.Constructor.params.success == 'function') this.Constructor.params.success(this.responseText);
					} else {
						// check aborted parameter, if aborted there is no need for an additional error
						if (!this.Constructor.aborted)
						{
							if (typeof this.Constructor.params.error == 'function') this.Constructor.params.error('404');
						}
					}
					break;
			}
		}	

		// send the package
		this.send = function()
		{
			if (this.params.crossdomain)
			{
				this.xmlhttp.open(this.requestType, '/ajax.php?method='+this.requestType+'&url=' + this.params.url, this.params.async);
			} else {
				this.xmlhttp.open(this.requestType, this.params.url, this.params.async);
			}

			if (typeof this.params.timeout != 'undefined')
			{
				this.timeout(this.params.timeout);
			}

			if (this.requestType == 'POST')
			{
				this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				this.xmlhttp.send(this.requestParams);
			}

			if (this.requestType == 'GET')
			{
				this.xmlhttp.send(null);
			}
		}

		// set a timer if necessary
		this.timeout = function(timer)
		{
			var Constructor = this;
			if (!this.timer)
			{
				this.timer = true;

				setTimeout(function() {
					Constructor.timeout()
				}, timer);
				return;
			}

			// if request not succeeded in the given time
			if (!this.success)
			{
				this.aborted = true;
				this.cancel();

				if (typeof this.params.onTimeout == 'function')
				{
					this.params.onTimeout();
				}
			}
		}

		// the cancel function
		this.cancel = function()
		{
			this.xmlhttp.abort();
		}

		// set the auto sender
		//if (params.autoSend) this.send();
		this.send();

	}

        ajax = new Ajax({
            url: url,
            async: true,
            requestType: 'GET',
            timeout: 5000,
            crossdomain: true,
            success: function(data)
            {
	          alert('success');
            },
            onTimeout: function()
            {
                alert('timeout');
            }
        });
    

Het php script

<?php
	if ($_GET['method'] == 'GET')
	{
		echo file_get_contents($_GET['url']);
	} else {
		// todo, post with cUrl
	}
?>
14
Sep 2011
POSTED BY
POSTED IN Javascript
DISCUSSION 0 Comments
TAGS

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>