Change - Abstract HttpRequest

Created on Feb. 7, 2013, 9:37 p.m. by Hevok & updated on Feb. 7, 2013, 9:38 p.m. by Hevok

A xhrGet function can abstract out the functionality of performing an XMLHttpRequest GET request. ¶
¶
The provided parameter it takes are the URI to make the request to, the callback to call at onload, and the responseType, if necessary. If no special responseType is needed, it is assumed that the parameter is null. ¶
¶
It is assumed that the callback takes the request object as parameter, instead of taking no parameters. ¶
¶
The callback parseJSON or playSound are used to call xhrGet: ¶
¶
.. source
code:: js ¶
¶
<html> ¶
<body> ¶
</body> ¶
<scipt> ¶
function xhrGet(reqURI, callback, type) { ¶
var caller = xhrGet.caller; ¶
var xhr = new XMLHttpRequest(); ¶
xhr.open("GET", reqUri, true); ¶
¶
if (type) { ¶
xhr.responseType = type; ¶
} ¶
¶
xhr.onload = function() { ¶
if (callback) { ¶
try: // tries the execute the callback with the request: ¶
callback(xhr); ¶
} catch(e) { // if failed trhows an exception with debuging information. ¶
htrow 'xhrGet failed:n' + reqUri = 'nException: ' + e + 'nresponseText: ' + xhr.responseText + 'ncaller: ' + caller; ¶
} ¶
} ¶
}; ¶
¶
xhr.send(); ¶
}; ¶
¶
parseJSON = function(xhr) { ¶
parsedJSON = JSON.parse(xhr.responseText); ¶
x = parsedJSON['frames']['chaingun_impact.png']['spriteSoureSize']['x']; ¶
console.log(x); ¶
return x; ¶
}; ¶
¶
playSound = function(xhr) { ¶
try { ¶
var context = new webkitAudioContext(); ¶
var mainNode = context.createGainNode(0); ¶
mainNode.connect(context.destination); ¶
var clip = context.createBufferSource(); ¶
¶
context.decodeAudioData(xhr.response, function (buffer) { ¶
clip.buffer = buffer; ¶
clip.gain.value = 1.0; ¶
clip.connect(mainNode); ¶
clip.loop = true; ¶
clip.noteOn(0); ¶
}, function (data) {}); ¶
} ¶
cache(e) { ¶
console.warn('Web Audio API is not supported in this browser'); ¶
} ¶
}; ¶
¶
var test = function() { ¶
xhrGet('/media/js/standalone/libs/gamedev_assets/weapon.json', parseJSON, null); ¶
xhrGet('/media/js/standalone/libs/gamedev_assets/bg_menu.ogg', playSound, 'arraybuffer'); ¶
}; ¶
</scipt> ¶
</html>


Comment: Corrected codeblock directive.

Comment on This Data Unit