javascript 如何从来自同一域的 iframe 访问 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6880967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access JSON from an iframe originating from same domain?
提问by Kumar
In my webpage a hidden iframe is loaded with some JSON in it. This JSON is refreshed by some actions on the page. How do I access this JSON in iframe from my web page? for some unknown arcane unexplainable reason I am forced to use jQuery 1.3.2. so no $.parseJSON()
在我的网页中,一个隐藏的 iframe 加载了一些 JSON。此 JSON 由页面上的某些操作刷新。如何从我的网页访问 iframe 中的此 JSON?由于某些未知的神秘无法解释的原因,我被迫使用 jQuery 1.3.2。所以不行$.parseJSON()
回答by Paul
I think you can use:
我认为你可以使用:
var json = $.parseJSON($("#hiddeniframe").contents().text());
Something along those lines will work at least.
沿着这些路线的东西至少会起作用。
回答by db48x
All modern browsers include a JSON parsing library:
所有现代浏览器都包含一个 JSON 解析库:
var data = JSON.parse($("#hiddeniframe").contents().text());
If you need to support older browsers there are several libraries to choose from that will provide the same interface. The better ones will check to see if the browser is providing a native implementation and not override it, since it's bound to be faster.
如果您需要支持较旧的浏览器,有几个库可供选择,它们将提供相同的界面。更好的将检查浏览器是否提供本机实现而不是覆盖它,因为它肯定会更快。
See also JSON.stringify()
也可以看看 JSON.stringify()
回答by Evi Song
The code @Paulpro posted:
@Paulpro 发布的代码:
var json = $.parseJSON($("#hiddeniframe").contents().text());
doesn't work for me.
对我不起作用。
I changed the code to:
我将代码更改为:
var json = $.parseJSON($("#hiddeniframe").contents().find("*").first().text());
And now it works.
现在它起作用了。