If you don't use jQuery, and want a nice short XHR2 which works on the modern browsers and also on the mobile browsers I suggest to use it this way.
function ajax(a,b,c){ // Url, Callback, just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
As you can see:
- It's shorter than all other functions Listed.
- The callback is set directly (so no extra unnecessary closures).
- It uses the new onload (so you don't have to check for readystate && status)
- there are some other situations which i don't remember that make the xhr1 annoying.
There are 2 ways to get the response of this ajax call(3 using the xhr var name):
The simplest
this.response
or if for some reason you
bind() the callback to a classe.target.response
Example
function callback(e){
console.log(this.response);
}
ajax('URL',callback);
or (the above one is better anonymous functions are always a problem)
ajax('URL',function(e){console.log(this.response)});
Nothing easier.
Now some ppl will probably say that it's better to use onreadystatechange or the even the XMLHttpRequest variable name. That's wrong.
Check this out: http://caniuse.com/xhr2
support on all *modern browsers. And I can confirm as I'm using this approach since xhr2 exists. I never had any type of problem on all browsers I use.
onreadystatechange is only useful if you want to get the headers on state 2.
Using the
XMLHttpRequest variable name is another big error as you need to execute the callback inside the onload/oreadystatechange closures else you lost it.
Now if you want something more complex using post and FormData you can easily extend this function:
function x(a,b,e,d,c){ // Url,callback,method,formdata or {key:val},placeholder
c=new XMLHttpRequest;
c.open(e||'get',a);
c.onload=b;
c.send(d||null)
}
Again ... it's a very short function but it does get & post
examples of usage:
x(url,callback);//by default it's get so no need to set
x(url,callback,'post',{'key':'val'}); //no need to set post data
or pass a full form element (
document.getElementsByTagName('form')[0])var fd=new FormData(form);
x(url,callback,'post',fd);
or set some custom values
var fd=new FormData();
fd.append('key','val')
x(url,callback,'post',fd);
As you can see I don't implemented sync... it's a bad thing.
Said that ... why don't do it the easy way?
As mentioned in the comment the use of error && synchronous does completely break the point of the answer.Which is a nice short way to use ajax in the proper way.
Errror handler
function x(a,b,e,d,c){ // URL,callback,method,formdata or {key:val},placeholder
c=new XMLHttpRequest;
c.open(e||'get',a);
c.onload=b;
c.onerror=error;
c.send(d||null)
}
function error(e){
console.log('--Error--',this.type);
console.log('this: ',this);
console.log('Event: ',e)
}
function displayAjax(e){
console.log(e,this);
}
x('WRONGURL',displayAjax);
In the above script you have an error handler which is statically defined so it does not compromise the function. The error handler can be used for other functions too.
But to really get out an error the only way is to write a wrong URL in which case every browsers throws an error.
error handlers are maybe useful if you set custom headers, set the responseType to blob arraybuffer or whatever....
Even if you pass 'POSTAPAPAP' as methot it won't throw an error.
Even if you pass 'fdggdgilfdghfldj' as formdata it won't throw an error.
In the first case the error is inside the
displayAjax() under this.statusText as Method not Allowed.
In the second case it simply works. You have to check at the server side if you passed the right post data.
crossdomain not allowed throws error automatically.
In the error response there are no error codes.
There is only the
this.type which is set to error.
Why add errorhandler if you totally have no control over errors? Most of the errors are returned inside this in the callback function
displayAjax()
So: NO need for error checks if your able to copy and paste the url properly. ;)
ps.: As the first test i wrote x('x',displayAjax).. and it totally got a response...??? so I checked the folder where the HTML is located .. and there was a file called 'x.xml'.. so even if you forget the extension of your file xhr2 WILL FIND IT I lol'd
Read a file syncronous
Don't do that.
if you wan't to block the browser for a while load a nice big txt file syncronous
function omg(a,c){ // Url
c=new XMLHttpRequest;
c.open('GET',a,true);
c.send();
return c; //or c.response
}
now you can do
var res=omg('thisIsGonnaBlockThePage.txt');
There is no other way to do this in a non asynchronous way.(yeah with setTimeout loop... but srsly?)
Another point is .. if you work with API's or just you own list's files or whatever you always use different functions for each request..
Only if you have a page where you load always the same XML/JSON or whatever you need only one function.In that case modify a little the ajax function and replace b with your special function.
the functions above are for basic use.
if you want to EXTEND the function ...
yes you can
I'm using a lot of API's and one of the first functions i integrate in every html page is the first ajax function in this answer ..with GET only...
but you can do a lot of stuff with xhr2:
I made a download manager (using ranges on both sides with resume,filereader,filesystem),various image resizers converters using canvas,populate websql databases with base64images and much more... but in thisc cases you should create a function only for that purpose... sometimes you need blob, arraybuffers, you can set headers , override mimetype and there is a lot more...
but the question here is how to return an Ajax response ... (i added n easy way)
############################################################## Disclaimer: The Best answers from stackoverflow.com has been listed here.
No comments:
Post a Comment