1

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?

Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105

1 Answers1

1

Your server script should do something like (this example is PHP):

echo $_GET['callback'] . '(' . json_encode($data) . ');';

What is JSONP all about?

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.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612