ρss
ρss

Reputation: 5315

Defining a callback function in JSON/JSONP

Level: Beginner

Hello all,

I am very new to JSON world and I have a confusion.
I am working on an API which states that I can get some information from the server by using JSON's callback function.

The API document gives a response as in the example below:

It says I can get some information by sending a request to server like this: www.myserver.com/id?jsonpCallback=mycallback

Further more it says that the request structure will be as below:

{
  "proto Version" : <String>,
  "sVersion" : <String>,
  "requestType" : <String>,
  "requestData" : <DataModel>
}

and the response structure will be like below:

{
  "protoVersion" : <String>,
  "sVersion" : <String>,
  "responseType" : <String>,
  "responseErrorType" : <String>,
  "responseErrorDetail" : <String>,
  "responseData" : <DataModel>
}   

My questions are the following:

  1. Where will this mycallback parameter will be defined? What could be the starting point? I guess I need to create a separate application that does this for me but not sure.
  2. Do I need to craft my request and response too? If yes, then where?
  3. Can I craft a request like below?

www.myserver.com/id?jsonpCallback={"proto Version" :1.2, "sVersion":3, "requestType" :String, "requestData" :DataModel}

It would be great if someone can point me to a good tutorial. I plan to use python language. Thank you for your time.

Upvotes: 0

Views: 153

Answers (1)

Quentin
Quentin

Reputation: 944054

Where will this mycallback parameter will be defined? What could be the starting point? I guess I need to create a separate application that does this for me but not sure.

Your client side JavaScript needs to create a global function with a unique name that accepts a single argument (which will be the data returned by the HTTP API).

You then use that name as the mycallback in the URL

Do I need to craft my request and response too? If yes, then where?

You craft the request by creating a script element, setting its src to the API URL (including your callback parameter), and appending it to the DOM

Can I craft a request like below?

No. jsonpCallback must be the function name.

Further more it says that the request structure will be as …

That structure makes no sense for a JSONP request.

It is usual to use standard query string arguments.

http://www.myserver.com/id?jsonpCallback=myhandler13487w8789&protoVersion=1.2&sVersion=3&requestType=String&requestData=DataModel

I plan to use python language.

Then don't use JSONP. It is a hack to work around the Same Origin Policy, which is a browser sandbox feature. Use regular JSON.

Upvotes: 1

Related Questions