How to know if the iframe content is html or json on load event

廉价感情. 提交于 2021-02-18 22:12:26

问题


I have an event handler function bound to the load event of an iframe, and I want to know if the content retrieved inside the iframe is HTML or JSON. Is there a way to achieve this?


回答1:


After some research, the most feasible way I found to know which kind of content is loaded in the iframe is trough the contentType/mimeType properties of the document DOM element. We can get this property in different ways:

Inside the load handler function (way 1):

var iframedocument = $(this).contents().get(0);
var contentType = iframedocument.contentType || iframedocument.mimeType;

Inside the load handler function (way 2):

var iframedocument  = this.contentDocument;
var contentType = iframedocument.contentType || iframedocument.mimeType;

Inside or outside the load handler function (way 3):

var iframe = document.getElementById('iframe_id');
var iframedocument  = iframe.contentDocument;
var contentType = iframedocument.contentType || iframedocument.mimeType;

If contentType == 'application/json' then the document loaded is JSON. If contentType == 'text/html' then the document is HTML.

Additional notes: The idea came from Geoff Wartz's answer to this question: how to listen for returned json object with jquery The solution was based upon the proposed answer to this other question: How to get content-type from an iframe?. Finally, we have to use contentType for Mozilla Firefox compatibility and mimeType for IE.



来源:https://stackoverflow.com/questions/12515135/how-to-know-if-the-iframe-content-is-html-or-json-on-load-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!