Rendering JSON in controller

后端 未结 3 1859
长情又很酷
长情又很酷 2020-12-07 09:43

I was reading a book and in a chapter about Controllers when it talks about rendering stuff, for JSON it has an example like this but doesn\'t go in to details so I couldn\'

3条回答
  •  执念已碎
    2020-12-07 09:57

    You'll normally be returning JSON either because:

    A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.

    or

    B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.

    Or, possibly, you are eating your own dogfood and doing both

    In both cases render :json => some_data will JSON-ify the provided data. The :callback key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)

    Why :callback?

    JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com and you will be serving your application off of services.yoursite.com your JavaScript will not (by default) be able to make XMLHttpRequest (XHR - aka ajax) requests from services to api. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:

    {"name": "John", "age": 45}
    

    the server instead would send back:

    valueOfCallbackHere({"name": "John", "age": 45})
    

    Thus, a client-side JS application could create a script tag pointing at api.yoursite.com/your/endpoint?name=John and have the valueOfCallbackHere function (which would have to be defined in the client-side JS) called with the data from this other origin.)

提交回复
热议问题