Crew algemeen |
|
Kan ook niet, het is asynchroon dus je onreadystatechange wordt later aangeroepen. Tegen die tijd is de functie allang klaar.
XMLHttp is makkelijk op te lossen als je het goed doet:
/*global P */
/*members ajax, handlers, json, onreadystatechange, open, parse,
protocol, readyState, request, responseText, send, setRequestHeader,
text
*/
P.ajax = (function (global) {
var xhr, handlers = {
text: function (txt) {
return txt;
},
json: function (txt) {
return JSON.parse(txt);
}
};
if (typeof XMLHttpRequest !== 'undefined' && (location.protocol !== 'file:' || typeof ActiveXObject === 'undefined')) {
xhr = function () {
return new XMLHttpRequest();
};
} else {
xhr = function () {
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
};
}
return {
request: function (url, func, type, method) {
var r = xhr(), stateChange;
if (!r) {
return;
}
if (!type) {
type = 'json';
}
if (!method) {
method = 'GET';
}
r.open(method, url);
r.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
r.onreadystatechange = stateChange = function () {
if (r.readyState === 4) {
func(handlers[type](r.responseText));
r = null;
}
};
r.send(null);
},
handlers: handlers
};
}(this));
/*global P */ /*members ajax, handlers, json, onreadystatechange, open, parse, protocol, readyState, request, responseText, send, setRequestHeader, text */ P.ajax = (function (global) { var xhr, handlers = { text: function (txt) { return txt; }, json: function (txt) { return JSON.parse(txt); } }; if (typeof XMLHttpRequest !== 'undefined' && (location.protocol !== 'file:' || typeof ActiveXObject === 'undefined')) { xhr = function () { return new XMLHttpRequest(); }; } else { xhr = function () { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} }; } return { request: function (url, func, type, method) { var r = xhr(), stateChange; if (!r) { return; } if (!type) { type = 'json'; } if (!method) { method = 'GET'; } r.open(method, url); r.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); r.onreadystatechange = stateChange = function () { if (r.readyState === 4) { func(handlers[type](r.responseText)); r = null; } }; r.send(null); }, handlers: handlers }; }(this));
En vervolgens:
P.ajax.request('image_print.php?url=' + url, function (response) {
if (response === 2) {
// doe iets, het is goed!
}
}); // JSON, GET
P.ajax.request('image_print.php?url=' + url, function (response) { if (response === 2) { // doe iets, het is goed! } }); // JSON, GET
|