32

Might be obvious, but still I'm lacking here of the basic knowledge.

So inside controllers, can both be used, or is it always Javascript, so both are the same?

1
  • I believe that both can be used because they're separate MIME types. Why not try it and see? Commented Feb 25, 2010 at 17:22

2 Answers 2

41

json and js are two different types of response and they are defined as different MIME types in Rails

Mime::Type.register "text/javascript", :js, %w( application/javascript application/x-javascript )
Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest )

Even if Json can be considered a subset of JavaScript, not all JavaScript responses are actually Json responses.

You might want to respond with Json and Js in the same action.

For instance, you might have an action that responds with Json to an API call and with JavaScript (perhaps using RJS) to an internal Ajax call.

Sign up to request clarification or add additional context in comments.

Comments

24

In Rails 3.1 the only difference I can spot is that the if formatter is js, then the answer is sent as plain text. If it is json then it is encoded as json.

if format.json

format.json {
  render :json => @accounts.map(&:attributes)
}

server send:

data:application/json;base64,

if format.js

format.js {
  render :json => @accounts.map(&:attributes)
}

server send:

[{"id":33,"email":"[email protected]"}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.