I wish to request data from a web service endpoint( say “http://www.example.com“) using javascript.
After retrieving it , there will be a callback function to process the response ( which will be a JSON object )
How do I go about writing it? A skeleton code will do.
Will it be something like:
<script>
function callback(data)
{
// the response text would be processed here.
}
url="http://www.example.com";
var script = document.createElement('script');
script.src = url;
script.onload=callback;
document.body.appendChild(script);
</script>
Thanks in advance.
As noted by @JuicyScripter in the comment above…
This means that you can add a callback to the query…
Notice at the end I added
&callback=my_callback. What will happen is that instead of sending a JSON response like……it will now be wrapped in a function call. This will be valid JavaScript, so your
scriptrequest will execute the function, and pass the data.So all you need is a callback function that has the same name as the function you gave in the query…
Make sure this function is globally available.
Then get rid of the
onloadline, and your code should just work…When the script arrives and runs, it will invoke your function passing it the data requested.