3 ms·
So far, this has worked perfectly for me: function ajax(url, post_parameters, callback, data) { var http = new XMLHttpRequest(); if (http != undefine
by PavlovsCat 13y ago
So far, this has worked perfectly for me:
function ajax(url, post_parameters, callback, data)
{
var http = new XMLHttpRequest();
if (http != undefined)
{
http.open(post_parameters == '' ? 'GET' : 'POST', url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function()
{
if (callback != null)
{
callback(this.readyState, this.status, this.responseText, data);
// readyStates: UNSENT = 0, OPENED = 1, HEADERS_RECEIVED = 2, LOADING = 3, DONE = 4;
}
};
http.send(post_parameters);
return true;
}
else
{
console.log("no ajax.. sorry.");
return false;
}
}
- rmrfrmrf 13y agoDoesn't work in IE and doesn't support cross-domain requests. Oh, and yes, I'm sure every user knows to check their javascript console when an app does nothing.
- k3n 13y agoI wonder if that code block does anything at all. var http = new XMLHttpRequest(); if (http != undefined) { ... } In what runtime would calling this constructor return undefined (or null, or false...), and yet not throw an error?
- rmrfrmrf 13y agoYou're right, that code will blow up if the browser doesn't support XMLHttpRequest. The version below is more common: var ajaxObject; if (window.XMLHttpRequest) { ... } else if (window.ActiveXObject) { ... } if (ajaxObject) { ... } else { //handle users without ajax } and that's just to create the object! compare to: $.ajax();
- PavlovsCat 13y agoand that's just to create the object! compare to: $.ajax(); So you're comparing the body of one function to the signature of another? I know I posted some really shitty code, but you managed to shoot yourself in the foot even in that scenario, grats. https://github.com/jquery/jquery/blob/master/src/ajax.js https://github.com/jquery/jquery/blob/master/src/ajax.js Here, now it's apples to apples.
- rmrfrmrf 13y agoyou realize i'm talking about code I have to write, right? If anything, you've further proven my point, considering that the jQuery implementation also covers other common use cases like failure, cross-browser requests, etc., i.e. hours upon hours of googling and/or just copy-pasting the jQuery source into my app, which adds loading time to my site instead of just using a cached version of jQuery that almost everyone already has in the cache in the first place.
- k3n 13y agoWhen I look at that, I see man-years of work that I don't have to reinvent.
- PavlovsCat 13y agoI already said it works perfectly for me - I don't care about IE (the feeling is mutual I think) and I don't request from other domains. The error message is useless/dumb, sure, but then again I didn't say you should use this, I said I use this. I'll improve it when I have actual need to do so, how's that for an idea.