The trick works by using a <script>
tag to load a JSON (e.g.: { "city":"Barcelona" }
) from somewhere else, butthat will send us the data wrapped in a function, the actual JSONP ("JSON with Padding"):
Receiving it in this way enables us to use the data within our tourismJSONP
function. JSONP is a bad practice and not needed anymore, don't use it (read belowat the end).
This is a Content Security Policy restriction error, it's designed to protect users from certain attacks. You should just configure it properly (see belowat the end).
How doeswould the JSONP trick help us here? Well, <script>
tags are not subjected to this whole server (origin1) restriction! That's why we can load a library like jQuery or Google Maps from any server.
Here's the important point: if you think about it, those libraries are actual, runnable JS code (usually a massive function with all the logic inside). But raw data? JSON data is not code. There's nothing to run; it's just plain text.
ThereforeHence, there's no way to handle or manipulate our precious data. Thethe browser will download the data pointed at by our <script>
tag and when processing it'll rightfully complain:
wtf is this {"city":"Barcelona"}
crap we loaded? It's not code. I can't compute, syntax error!
The old JSONP hack
The old/hacky way to utilize that data? If only we could make plain text somehow runnable, we could grab it on runtime. So weWe need anotherweb.com
to send it with some logicas it if were code, so when it's loaded, your code indownloaded the browser will be able to use said datarun it. We just need two things: 1) to get the data in a way that it can be run, and 2) write some code in the client so that when the data runs, this codeour function is called and we get to use the data.
For 1) we askif the foreign server to send us the JSON data inside a JS function. The data itself is set up as that function's input. It looks like this:
tourismJSONP({"city":"Barcelona"})
which makes it JS code our browser will parse and run without complaining! Exactly like it does with the jQuery library.
To receive the data like that, the client "asks" the JSONP-friendly server friendly we'll ask for it, usually donethe data like this:
So we'll receive it like this:
tourismJSONP({"city":"Barcelona"})
which now makes it JS code that we could interact with.
As per 2), since our browser will receive the JSONP with that function name, we need to write a function with the same name in our code, like this:
- origin is defined by 3 things: protocol, port, and host. So, for example,
https://web.com
is a different origin than http://web.com
(different protocol) and, also https://web.com:8081
(different port) and obviously https://thatotherweb.net
(different host)