Viral Viral - 1 year ago 165
JSON Question

JSONP with native XMLHttpRequest

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

Response I get is:





Currently, I am doing weird thing like:


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)

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

JSBin for ajax script


Answer Source

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.