代码点火器在访问 URL 时提交表单

Codeigniter submit form when accessing URL

本文关键字:提交 表单 URL 访问 点火器 代码      更新时间:2023-09-26

我有一个表单,当我点击提交按钮时,它完美地工作。我想要的是,如果我在URL中添加参数,它会在访问URL时自动提交表单。

我的表单看起来像这样:

<form id="form_group_data" name="form_group_data"  method="post" class="form-horizontal" action="<?php echo site_url('admin/group/add')?>">
   <p>
   <div class="form-body">
      <div class="form-group">
         <label class="col-md-2 control-label" for="name">Name<span class="required"> * </span></label>   
         <div class="col-md-4">
            <input id="name" class="form-control" type="text" name="name" required="required" value="">
         </div>
      </div>
      <div class="form-group">
         <label class="col-md-2 control-label" for="firstname">Firstname<span class="required"> * </span></label>   
         <div class="col-md-4">
            <input id="firstname" class="form-control" type="text" name="firstname" required="required" value="">
         </div>
      </div>
      <input type="submit" value="Ajouter" class="btn blue"/>
      <button type="button" class="btn default" onclick="window.location='<?php echo site_url('admin/group')?>'">Annuler</button>
   </div>
   </p>
</form>

如果我手动填写字段并提交,它就可以了。现在我可以输入此 URL,它通过 URL 中的参数填充字段,但我希望它也自动提交,而无需单击提交按钮。

自动填充字段的示例 URL:https://test.ch/admin/user/insert/John/Lennon

可能吗?也许用JQuery?

  • 检查网址参数是否存在
  • 如果是,假设表单填写了来自 URL 的数据,请使用 jQuery 提交它

将此代码放在结束正文标记之前

<?php 
if(isset(your_url_parameters)) // check if all parameters exist in url
{ ?>
<script type="text/javascript">
    $( document ).ready(function() {
        $("#form_group_data").submit(); //submit the form
    });
</script>
<?php } ?>

如果您能够填写表单 - 您正在设置此URL - 那么您也可以将此数据发送到已经处理表单提交操作的其他 URL。因此,与其在填写数据后尝试四舍五入提交此表单,不如首先使用这些参数将其指向操作 url admin/group/add/other/params/here,并在该控制器中检查这些参数。但是请注意,在这种情况下,您将回避CSRF保护并打开潜在的漏洞。如果启用了该保护,则最好使用 csrf 令牌以及要发布的数据发布到此终结点。

或者,您可以使用此表单的控制器来检查 url 中是否设置了参数。您应该能够检查参数,如果设置了参数(如果要这样做,请通过验证),请执行通常在表单提交中执行的操作。

if (isset($this->uri->segment(4)) && isset($this->uri->segment(5)) {
    // Do the work here - add to db, etc. Alternatively call the function 
    // that is supposed to do the work and pass these parameters in some way.
    $this->load->model("my_user_model");
    $this->my_user_model->add_user($this->uri->segment(4), $this->uri->segment(5));
    redirect("success/url");
}

这只是一个例子。您需要清理和验证您处理的任何表单数据,因此在这种情况下,my_user_model->add_user需要执行此操作,或者理想情况下,您将在模型之前使用 CI 的表单验证库执行此操作。

我强烈建议查看表单验证文档,作为如何使用CI的内置功能处理表单和提交数据的一个很好的例子。