Viral Viral - 5 months ago 41
JSON Question

JSONP with native XMLHttpRequest

I am trying to make API call to twitch with callback.

https://api.twitch.tv/kraken/search/streams?limit=25&offset=0&q=war&callback=responseReceived

Response I get is:

/**/responseReceived({"_total":959,"_links":

{"self":"https://api.twitch.tv/kraken/search/streams?

.....

"}}}]})


Currently, I am doing weird thing like:

callback(JSON.parse(xhr.response.split('responseReceived(')[1].split(")")[0]));


which is not right coz this might break for sure. I did google but only of 2 things come up


  1. append script tag with src as api (which works but I want to see if I can use XMLHttpRequest())

  2. jQuery (which i don't want)



Question:
1. in vanilla JS option 1 is the only way? or
2. any suggestions

JSBin for ajax script

Thanks

Answer

JSONP is a JavaScript program and there is no good way to parse it. You either have to trust that it isn't going to vary the format or you have to execute third party code (the latter being how it is designed to be used, it's a relatively dangerous hack, which is why we now have CORS so we don't need JSONP). You could also write a complete JavaScript parser (in JavaScript!) and use it to find the function with the name that matches the callback, but that's rather non-trivial.

There is a third way though. If you remove callback=... from the URL then the service will return JSON instead of JSONP. Then you can just use JSON.parse() cleanly.