📜 ⬆️ ⬇️

Cheat Sheet => Cross Domain AJAX. Dynamic script Tag Hack

It happened historically (due to security reasons) that the Javascript object XMLHttpRequest , which underlies AJAX, cannot make cross-domain calls. This is a useless limitation: for intruders does not pose a particular problem, and for developers it creates some inconvenience. The next generation of browsers promised to solve this problem, but not earlier than the W3C at least approves of new standards.

There is a sea of ​​hacks to get around this limitation, but the most popular is Dynamic Script Tag Hack . It is through this hack that access to many APIs of modern web applications is organized.


')

The essence


XMLHttpRequest is not used at all. The page dynamically creates a tag and specifies the target address on another domain. The browser in the background will trigger and execute the contents of the remote script. The remote script itself transmits JSON data and is a simple function call of the form:

callback_function (json_data);

The `callback_function` function must be on the page and be visible globally. It will process the data returned in JSON. The name of this callback function must be either known in advance both on the client side and on the server side, or transferred by the GET parameter, for example:

src="http://example.com/api.js.php?callback_func=mycallback"

Accordingly, a remote script that outputs JSON data should look something like this.

<? php print $ _GET ['callback_func']. '('. json_encode ($ somedata). ')'; ?>

"Conclusion"


The hack itself is very easy to use, however, some developers cannot understand it.
It is very convenient to parse JSON data on the client side. If you need more info, here’s a nice article: An Introduction to JavaScript Object Notation (JSON)

Transferred from a personal blog as soon as it gained enough karma

Source: https://habr.com/ru/post/63353/


All Articles