Jquery $.ajax() json call to *.js file causes browser to ask 'save/open'

∥☆過路亽.° 提交于 2019-12-25 11:42:26

问题


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.


回答1:


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);
}



回答2:


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!




回答3:


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



来源:https://stackoverflow.com/questions/842399/jquery-ajax-json-call-to-js-file-causes-browser-to-ask-save-open

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!