Reputation: 27043
I want to execute a javscript callback from within the <script>
tag after loading a javascript file, using query string callback=MyCallbackFuntion
.
Something similar to
<script src="http://gdata.youtube.com/feeds/users/USER/uploads?
alt=json-in-script
&max-results=30
&callback=listVideosCallback"
type="text/javascript"></script>
Here at the end of src=http://...
, youtube uses the query string ?callback= listVideosCallback
to execute the function listVideosCallback()
after the data/file is loaded. How can I do something similar?
Upvotes: 1
Views: 2604
Reputation: 781726
Your server script should do something like (this example is PHP):
echo $_GET['callback'] . '(' . json_encode($data) . ');';
When you use <script src="URL"></script>
, the browser downloads the URL, and then executes the Javascript code that it contains. If that code looks like:
MyCallbackFunction(data);
then loading the script will cause the function to be called with the data as a parameter. So the server script should get the function name from the callback
URL parameter, and turn it into a function call by putting parentheses and a literal data object after it and echoing this.
Upvotes: 1