发布到iframe,但iframe将顶部窗口重定向到操作url,而不是self


Posting to iframe, but the iframe redirects the top window to action url instead of self?

我正在使用这里提到的表单post加载一个带有一些post数据的iframe:

你如何在iframe上发帖?

一切都很好。但是,如果我的iframe url中有重定向(通过头或javascript片段),它不会重定向到iframe中的下一个url,而是重定向父窗口。

例如:发布到iframe:

<form action="do_stuff.aspx" method="post" target="my_iframe">
  <input type="submit" value="Do Stuff!" />
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.php"></iframe>

not_submitted_yet.hp:

<?php
// DO some stuff with post data 
// redirect to a success url
header("Location: THE_URL");
?>

问题是The_URL并没有在iframe本身中打开,而是在完整的浏览器窗口中打开,这是一种不希望出现的行为。我该怎么解决这个问题?firefox和chrome的行为相同。

我认为这里可能发生的事情是THE_URL是一些破坏框架的受保护页面。也许是维基百科或其他网站。使用这样的代码:

if (top.location != location) {
    top.location.href = document.location.href ;
  }

这并不能直接回答您的问题,但既然您已经在使用javascript,为什么不通过AJAX帖子提交表单呢?返回新URL的jQuery帖子可以工作:

var submitData = $('#yourForm').serialize();
$.post('/your/url', submitData, function(data) {
    // Probably put some validation on the value coming back in data.
    window.location.href = data;
});

您可以尝试使用php函数file_get_contents,而不是头重定向。

<?php
$success_page = file_get_contents('http://www.example.com/');
echo $success_page;
?>