when you want to fake an ajax call, that's because your server's web service is just not ready yet, and whenever that web service is ready, switching back to it should cost nothing..
with jquery.ajax.fake
you simply write pure jQuery ajax call, with only one extra property fake: true
include jquery.ajax.fake.js
script into your markup, and create webservices.fake.js
to handle fake ajax calls
<script src="jquery.ajax.fake.js"></script>
<script src="webservices.fake.js"></script>
now lets say you want to fake a twitter timeline ajax call,
first simply create a fake web service in webservices.fake.js
using the same url that you would use in your ajax call as a first parameter
$.ajax.fake.registerWebservice('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=anasnakawa', function(data) {
return [{
"text": "hey this is fake #tweet, retweet please :) #retweet"
}]
});
now all you have to do is to add the property fake: true
to your ajax call settings... and that's it!
$.ajax({
type:'GET',
dataType:'jsonp',
fake: true, // <<<---- that's it !
url:'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=anasnakawa',
success:function(data, textStatus, XMLHttpRequest) {
// your fake tweet should be here!
}
});
you can disable fake ajax calls globally by either remove both jquery.ajax.fake.js
& webservices.fake.js
script files from your markup,
<!--
<script src="jquery.ajax.fake.js"></script>
<script src="webservices.fake.js"></script>
-->
or by just adding the following variable
$.ajax.isFake = false; // this will disable all fake ajax calls, and make the actual jQuery ajax handler work instead
don't worry, even fake ajax calls will work perfectly with Deferred
objects that implements the Promise
interface, as expected a fake ajax call will return a deferred object that will have a success & error methods
var deferred = $.ajax({
type:'GET',
dataType:'jsonp',
fake: true, // <<<---- that's it !
url:'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=anasnakawa'
});
deferred.done(function(data) {
// your fake tweet should be here!
}).fail(function() {
// handle some errors
});
bower install jquery.ajax.fake
yeoman install jquery.ajax.fake
$.ajax({
fake : false, // is it fake ?
wait : 1000 // how long should wait before return ajax response
});
- failed requests
created by Anas Nakawa github, twitter,
Released under the MIT License