I’m am very confused regarding the callback function while using jsonp
Here is my js file in json format
http://asla.dev.1over0.com/Guide/js/testjson.js
Essentially it’s this json
{"x": 10, "y":15}
This is the data I will be retrieving
Here is my website the client who wants to take in the data from the js file that lives cross-domain
http://www.waveofcolor.com/faq.php
in order for me to retrieve that data in the js file I have to include the js file
http://asla.dev.1over0.com/Guide/js/testjson.js within a script tag
and also declare a function to tell the page what to do with this data
here is the code
function func(json){
alert(json.x)
}
<script type="text/javascript" src="http://asla.dev.1over0.com/Guide/js/testjson.js"></script>
I guess this is the part in which I am confused; I’ve read so far that you pretty much just add a query string to the end of the js file you are calling within the script tag
<script type="text/javascript" src="http://asla.dev.1over0.com/Guide/js/testjson.js"></script>
will now be
<script type="text/javascript" src="http://asla.dev.1over0.com/Guide/js/testjson.js?jsonp=func"></script>
My question is… How does jsonp know to call the func function?
Would this need to be set up on the back end?
If so how does one set this up using either PHP or .NET 4.0 Framework.
I got jsonp to work if I hardcode and call the func function within the js file like so
func({ "x": 10, "y": 15});
But it doesn’t make sense to call the actual function within the js file right?
As always any input is appreciated
Yes, you’re correct. True JSONP requires back-end support. Normally, the JSON you’re returning will also be dynamic. If it’s not (there’s just one chunk of data everyone shares), hard-coding a function name (pick a better one than
func) is crude but effective.If you want actual JSONP, there are various ways to do it on the backend. See this trivial PHP example and this question about JSONP on ASP.NET MVC