Reading data from iframe to use the data for conditional judgements
I am creating a page to upload images without refreshing the page using an iframe. What I want to do is upload the image with forms through an iframe and use the result for a conditional task. I tried these methods:
<iframe id="iframe" name="iframe">Inner code here, form and all inputs. </iframe>
<script>
data=document.getElementById("iframe").innerHTML;
</script>
But this don't work开发者_JAVA技巧 as iframes work with source property only. Then i tried getting the body of iframe using window property.
data=window.frames['iframe'].document.body.innerHTML;
But this is also not working. Help. Thanks in advance.
I'm not entirely clear on what you are trying to do, so I will just list what I see as potential problems with the code that you posted.
- When using an iframe tag, any text between the opening and closing tags is only displayed in browsers that don't support iframes. The content of the iframe is loaded from the url assigned to the src attribute of the iframe element.
- In order to get the document containing the content of an iframe, you must access the iframe element as an IFrame object as opposed to a Window object. To do this, you must use
document.getElementById()
(as you did in your first code snippet); you cannot use thewindow.frames[]
array. - In your second code snippet, you try to access an element of the
window.frames[]
array by using the frame's name as the index; this is not allowed. You can either use a numerical index into the array, or access the frame by using it's name as a property of the window, e.g.window.iframe
. - Once you have obtained an IFrame object using
document.getElementById()
, you can use thecontentDocument
property of that object to get the document holding the content of the iframe. Using this object, you can callgetElementById
, etc. to retrieve the desired content from the iframe. - One final note: be aware that the same-origin policy governs your ability to access properties of the iframe from another window or frame. Specifically, the domain of the source of the iframe must be the same as the domain of the document containing the script that is trying to access properties of the iframe.
精彩评论