Dakota
Dakota

Reputation: 5

fetching json from iframe -- not jsonp

How can i get json from an iframe, it is not jsonp here is what i have. (using javascript only of course)

<script type="text/javascript">
var theFrame = document.getElementById('iframe');
            var theWin = theFrame.contentWindow;
            var theDoc = theFrame.contentDocument || theFrame.contentWindow.document;
var json = theDoc;
var msgs = JSON.parse(theDoc);

for (var i = 0, l = msgs.length; i < l; i++) {
    var msg = msgs[i];
    var div = document.createElement('div');
    div.innerHTML = 'Hello ' + msg.user + ' your Id is: ' + msg.ID + 'and your message is: ' + msg.message + ' it has ' + msg.replies + ' replies';
    document.body.appendChild(div);

</script>

<iframe id="iframe" name="iframe" src="http://jsonsource.com/not/jsonp/" width="100" height="100">
  <p>Your browser does not support iframes.</p>
</iframe>

Upvotes: 0

Views: 5205

Answers (2)

PeregrineYankee
PeregrineYankee

Reputation: 75

You can get what you want by accessing the iframe’s contentDocument.documentElement.textContent property. (In IE, it’s innerText instead of textContent.)

Upvotes: 0

Quentin
Quentin

Reputation: 943639

An iframe is subject to the same origin policy as XHR. So if your goal is to get around that, forget it. If your goal isn't to get around that, why would you use an iframe instead of XHR (which has a much nicer API)?

That said, the only thing obviously wrong with the code is that you try to access the iframe before it exists. Move the script to after it.

Upvotes: 2

Related Questions