I have some code that requests some JSON from an API. When data is returned, per the documentation, it sends back a callback function that is to be used to parse the data at the top level. After the call is made, I have the following code to capture the data and process it:
var callback = 'functionUsedInApiCall';
window[callback] = newCallBackFunction;
How would I go about passing custom params to the callback function above as the data is being returned?
In order to capture the data, I must write the callback function like this:
function newCallBackFunction(root) {
//root is the data
}
Any help would be greatly appreciated.
Are you talking about JSONP? If so, you don’t call the callback or pass in the argument at all, the code returned by the API does.
E.g., your code:
(I’m assuming this isn’t at global scope, hence assigning to the
windowobject.)…plus your code for initiating the JSONP call, which is usually appending a
scriptelement to your page with a URL containing the name of the callback (“myCallback” in the above).Their response will look like this:
…which, when it arrives, will run (because it’s the content of a
scriptelement), and will call your function. This is how JSONP works.If you want to include further arguments for the function, all you do is have the callback they call turn around and call your target function, e.g.:
Now when their code calls the global
myCallback, all it does is turn around and callnewCallbackFunctionwith that data and the arguments you specify.Those arguments don’t have to be literals as in the above. Here’s an example with a bit more context, using a closure:
Ideally, though, when doing JSONP you auto-generate the name of the callback each time so that it’s specific to the request (in case you have two outstanding requests at the same time):