gpt4 book ai didi

javascript - 从 iframe 获取 json——而不是 jsonp

转载 作者:行者123 更新时间:2023-12-02 20:25:17 24 4
gpt4 key购买 nike

我如何从 iframe 获取 json,这里不是 jsonp,这是我所拥有的。 (当然仅使用 JavaScript)

<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>

最佳答案

iframe 与 XHR 遵循相同的来源策略。因此,如果您的目标是解决这个问题,那就忘记它吧。如果您的目标不是解决这个问题,为什么要使用 iframe 而不是 XHR(它有更好的 API)?

也就是说,代码中唯一明显错误的是您尝试在 iframe 存在之前访问它。将脚本移到其后面。

关于javascript - 从 iframe 获取 json——而不是 jsonp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4927359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com