Search code examples
javascriptjsonp

How do I get json string from json?callback?


How do I get the json string when provided only with a url?

I have a url provided:

https://example.com/something.json?callback=getAppData

which I use as such:

<script src="https://example.com/something.json?callback=getAppData"></script>
<script src="appData.js"></script>

appData.js:

window.addEventListener('load', function () {
    console.log('appData');
    var data = getAppData();
    console.log(data);
}, false);

This logs nothing obviously. How do I get the json data? I am not using jQuery and this is a node.js app with mongoose.

Any direction is as always greatly appreciated, so thanks in advance!


Solution

  • When the JSONP request is made, it will call the passed callback function, which will need to be defined by you. This function will receive the data.

    <script>
        function getAppData(data) {
            console.log(data);
        }
    </script>
    <script src="https://example.com/something.json?callback=getAppData"></script>
    

    Usually you would add the <script> tag programatically, so you can make the call whenever you want.