views:

1005

answers:

3

I'm able to issue $.ajax() requests to urls that have a '.js' extension just fine when I use {...'dataType' : 'script'...}. However, when I use {...'dataType' : 'json'...} the browser (Opera and FF, so far, but I'll bet it's universal) asks to save/open the results of the request.

Note that my 'success' callback runs fine and uses the resulting json object just fine.

My question is, should I just drop the *.js extension from the resource and pass a 'json=true' option? Or is there a handy way to stop the browser from trying to render/save/open the result? (By handy I mean, of course, not something that every user has to set in their browser.)

Also note that I'm using Rails, so the header order routing issue prevents me from using an Accept header to fix this.

A: 

Well, the 'correct' file extension for a JSON file is .json, not .js. Have you tried that?

TM
This may be the case. The action in question is a post, however, and Rails seems to disallow posts for json objects. I was hoping to get the results back as json and then post them. I think, instead, I'll get them as text and do the processing on the client side.
Mike
+3  A: 

I might be wrong here, but I suspect you forgot to return false from your event handler. So your request is being propagated to the default handler. Or as pointed out by nickf a bug that causing your script to fail. Try to wrap your code in a try catch and see if you get any error:

try {
   // your code
} catch(e) {
   alert(e);
}
Nadia Alramli
agreed .. there might be a bug somewhere which is stopping your javascript code from completing, and hence just sending through the plain http request for a JS file.
nickf
No dice. I suspected there was no exception because the callback was running and all of it's intended actions were being rendered. I wrapped the body of the callback, as well as the body of the .js file in try blocks, and had alerts both as you suggested and after the catch blocks (to ensure that these bits of code were even being executed--It can be a pain to navigate your Rails routes sometimes!)All code executed just fine, I saw all alerts, and I have to presume that everything returned ok, just because the last alerts were on the line before the return statements.Oh well.
Mike
+1  A: 

Oh. This is a riot. Apparently, it's important not to comment out the statement 'return false;' at the end of your event handlers.

I must have inadvertently done so while commenting out some other code near the end of the handler.

Stay tuned for more 1337 h4x0r advice in teh future!

Mike