Monday, 17 August 2009

Using jQuery to make HTTP GET requests for JSON functions in ASP.NET MVC ...

Doesn't work for IE...because IE caches the results of the $.getJSON(...) HTTP GET query and you end up with the appearance of the same response every time

For example, I was writing some code that required a countdown this-evening and everytime I refreshed my IE window, I was starting from the same place I sarted before - e.g. if there were 32 minutes 7 seconds remaining on the counter, the counter counts down 10 seconds and you refresh the browser, you end up back at 32 minutes 7 seconds...frustrating, cause (of course) the problem only occurs in IE!

Way to solve it is the use a POST request. Go into your jquery-1.3.2.js file (or whatever version you're using), and find the getJSON method that you're using the make the GET request. Underneath that, paste in the following code:

postJSON: function(url, data, callback) { 
   return jQuery.post(url, data, callback, "json");
},

...then simply change the javascript methodcall you're making to postJSON instead of getJSON. Oh, and you'll need to decorate the method you had exposed in your ASP.NET MVC controller with the [AcceptVerbs(HttpVerbs.Post)] attribute, so as it knows it's a POST method. Apparently it's officially acceptable to cache the output of the HTTP GET command, because of it's idempotent nature: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

So I guess despite my frustration, I learnt two new things today; the real intention of the HTTP GET command and the word 'idempotent' ;-)

No comments:

Post a Comment