如何在加载事件中知道 iframe 内容是 html 还是 json [英] How to know if the iframe content is html or json on load event
问题描述
我有一个绑定到 iframe 的 load 事件的事件处理函数,我想知道 iframe 中检索到的内容是 HTML 还是 JSON.有没有办法做到这一点?
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?
推荐答案
经过一番研究,我发现最可行的方法是通过 contentType/mimeType 文档 DOM 元素的属性.我们可以通过不同的方式获得这个属性:
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:
在负载处理函数内部(方式 1):
Inside the load handler function (way 1):
var iframedocument = $(this).contents().get(0);
var contentType = iframedocument.contentType || iframedocument.mimeType;
在负载处理函数内部(方式 2):
Inside the load handler function (way 2):
var iframedocument = this.contentDocument;
var contentType = iframedocument.contentType || iframedocument.mimeType;
在负载处理函数内部或外部(方式 3):
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;
如果 contentType == 'application/json'
那么加载的文档是 JSON.如果 contentType == 'text/html'
那么文档是 HTML.
If contentType == 'application/json'
then the document loaded is JSON. If contentType == 'text/html'
then the document is HTML.
附加说明:这个想法来自 Geoff Wartz 对这个问题的回答:如何使用 jquery 侦听返回的 json 对象 解决方案基于对另一个问题的建议答案:如何从 iframe 获取内容类型?.最后,我们必须使用 contentType
来兼容 Mozilla Firefox,使用 mimeType
来兼容 IE.
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.
这篇关于如何在加载事件中知道 iframe 内容是 html 还是 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!