如何从iframe内部的表单中获取POST数据


How to get the POST data from a form inside of an iframe

我在CodeIgniter应用程序的iframe中有一个表单:

<div class="settings"><h2>Einstellungen</h2>
  <div class="main-content">
    <iframe src="" name="main-content">
      <form id="new-role-form" method="post" action="<?php echo base_url('index.php/home/settings') ?>">
        <input class="role-input" type="text" placeholder="Rolle" name="role"><input class="role-input" type="password" placeholder="Passwort" name="password"><button class="button role-submit" type="submit"><span class="glyphicon glyphicon-plus"></span></button>
      </form>
    </iframe>
  </div>
</div>

当提交此表单时,应该执行以下代码(提交正在运行,我测试了它;我可以在这里获得表单的输入):

$(document).on('submit', '#new-role-form', function(event) {
            var form = $(this);
            var name = $('input[name="role"]', form).val();
            var password = $('input[name="password"]', form).val();
            $.ajax({
                url: '<?php echo base_url('index.php/ajax/insertRole'); ?>',
                type: 'POST',
                data: {name: name, password: password},
                success: function() {
                    alert("success");
                }
            });
            event.preventDefault();
        });

这是我的ajax控制器的insertRole函数:

public function insertRole() {
        $this->Database->insert($this->input->post('name'), $this->input->post('password'));
    }

这就是我得到错误的地方:...index.php/ajax/insertRole 500 (Internal Server Error)

如何从iframe内的表单中检索POST数据?

如果在捕获"提交"事件时遇到问题,可以使用以下方法:

<script type="text/javascript">
    $('#frame').load(function() {
        $(this).contents().find('form').submit(function() {
            //do your stuff here
        });
    });
</script>

为了"等待"正在加载的iframe,然后捕获提交事件。您也可以在主文件中创建一个函数:

function valueFromIframe(val) {
   alert(val)
}

并从iframe:呼叫

<script type="text/javascript">
 parent.valueFromIframe("Hello world");
</script>

希望它能帮助