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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Don't forget the empty parenthesis ;)
Where exactly should this line go ?!
In the server script that you're running with the <script> tag.
I've added some more explanation, I hope it helps.
make no sense to me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.