-1

I understand that the key concept behind JSONP is that <script> tags
are the only elements that bypass javascript same origin policy. So using these tags we can load third party data disguised as js code.

I don't quite understand how JSONP is used in conjuction with AJAX.

My best guess is that:

when an AJAX call is made under the hoods a <script> tag elements is actually written in the document on the exact moment the AJAX request has to be made and therefore its result is immediately evaluated.

Can you help me with these also providing a simple example ?

thanks

GionJh
  • 2,742
  • 2
  • 29
  • 68
  • I don't think my question is a duplicate. In the questio you linked there's no mention to AJAX. – GionJh Sep 27 '15 at 14:15

1 Answers1

0

It works exactly the way you thought it should:

JSONP via XHR

It adds an async script tag into head, and immediately removes it after calling the callback function.


Update

Only to inform, I was using the JSONP flickr API in the example above:

setTimeout(function() {
  $.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?', {
      tags: 'jquery',
      tagmode: 'any',
      format: 'json'
    },
    function(data) {
      $.each(data.items, function(i, item) {
        $('<img />').attr('src', item.media.m).appendTo('#images');
      });
    });
}, 2000);
Buzinas
  • 11,597
  • 2
  • 36
  • 58