I understand the idea behind jsonp and I'm sure there is a reason for not doing the following but I am curious as to what that is.
Why (due to security, ease of use, etc.) would one not create an API such as the following?
http://www.something.com/json/?caller_var_name=the_var
returning JavaScript containing:
the_var = {"my": "json", "content": 1};
On the client, the code would look like:
<script>
var the_var;
</script>
<script src="http://www.something.com/json?varname=the_var"></script>
// the_var now contains the requested JSON data
This seems straightforward and I've tested it cross domain but as mentioned, I'm sure those that thought of JSONP had a reason for not doing the above. Why is that?
The point of using a "callback" function is that you get called back. The script does load asynchronously, and when it does get you automatically get your function called - it is as if the JSONP script fires a listener.
Of course, the approach with the variable would work as well, especially for synchronously loading scripts. However, when using asynchronous loading we would need to poll for the variable value being set, or use a DOM event for executing scripts. The former is despised, the latter is (and especially was) complicated because of inconsistent browser apis.
Notice that if you want to do this nonetheless, the common JSONP apis can be used with your "variable style" by putting ?callback=the_var%3D
in the URL parameter.