Ajax between domains - how to do?

Asked

Viewed 464 times

2

I need to do an Ajax for a webservice that is in another domain, because a browser security policy is not possible. You can do this via JSONP?

1 answer

0

Who will decide whether the call between domains will be possible is the server. There are basically two ways the server release calls cross-Domain. JSONP is one of them, where the server returns the response of the call wrapped in a function call. For example, if a "normal" response to service would be the following:

{ "nome": "Scooby Doo", "idade": 10 }

If the server supports JSONP, and the client (browser, via ajax) requests the response via a function called 'myFuncao', the answer would be as follows:

minhaFuncao({ "nome": "Scooby Doo", "idade": 10 });

With this, the client (application running in the browser) can use the tag <script> (that has no limitations cross-Domain) and call a function that is defined on the page. Libraries like jquery hide most of these details, so the call to the application seems to be a normal call.

So back to your original question: yes, it is possible to call between domains via JSONP if the webservice supports JSONP. As shown above, the service needs to return a different response, so the solution cannot be made only on the customer side.

Note that there are still other ways to enable the call cross-Domain by clients. JSONP supports only calls that use the HTTP method GET - POST, PUT, etc. are not supported. For other methods, CORS (Cross-Origin Resource Sharing) is an alternative, and is supported by most modern browsers (Chrome, Firefox, Safari, IE10+). Like JSONP, the server plays an active role in enabling calls.

Another alternative, if the server does not support CORS or JSONP is the use of a service (web service) that serves as a proxy, forwarding calls from your client to the final server. The advantage is that since the proxy is not running in a browser, it has none of the restrictions of cross-Domain; however, the proxy loses customer context (for example, if the web application uses cookies to log in to the service, the proxy will not have cookies and their calls will be anonymous).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.