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 restriction: for attackers it does not present a particular problem, but for developers it creates some inconvenience. The next generation of browsers promised to solve this problem, but not earlier than W3C at least approve new standards.

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



    Essence


    XMLHttpRequest is not used at all. A tag is dynamically created on the page and the target address on another domain is indicated. The browser in the background will load and execute the contents of the remote script. The remote script itself transmits JSON data and is a regular 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 should either be known in advance both on the client side and on the server side, or passed in a GET parameter, for example: Accordingly, a remote script that produces JSON data should look something like this

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





    "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 additional info, here is a good article: An Introduction to JavaScript Object Notation (JSON)

    Moved from a personal blog as soon as I got enough karma

    Also popular now: