PHP POSTing/submitting 表格信息错误

PHP POSTing/submitting wrong information through forms

我正在动态生成 FORMS,每个表单都有一个 ID 作为 GET 变量。所以假设有两种形式:

<form action='website.com/controller?id=1'>
  <input type="submit" name="submitting">
</form>

<form action='website.com/controller?id=2'>
  <input type="submit" name="submitting">
</form>

现在,由于一些奇怪的原因,我在控制台中看到 POST 请求,如:

http://website.com/controller?id=2

对于这两种形式。在提交这两个表单时,我看到相同的 POST 请求。

PS: 我正在修改一个 Prestashop 模块。

这应该有效:

<form action='website.com/controller' method='get'> 
<Input type='hidden' name='id' value='1'>
<input type="submit" name="submitting"> </form>
 <form action='website.com/controller' method='get'> 
<Input type='hidden' name='id' value='2'>
<input type="submit" name="submitting"> </form>

如果您在页面加载后动态添加表单,并使用事件处理程序提交它们,则需要使用事件委托。

事件处理程序必须附加到页面加载时存在的元素。您不能将处理程序附加到稍后在页面加载后动态添加的元素。

解决这个问题的方法是使用 event delegation。例如:

$('form').on('submit', function() {
    // This will handle any form which exists at page load.  Any form
    // dynamically added later will not be handled.
}

$('body').on('submit', '#someFormID', function(e) {
    // This is attached to the parent body element, which of course exists
    // on load, and will handle submission of anything in the body, even
    // those which did not exist at page load.  You can then filter to
    // match only elements matching the next parameter - eg in this case
    // handle only something with id 'someFormID'.
}

$('body').on('submit', function(e) {
    // You can also dynamically work out which form has been submitted
    var $button = $(e.target),
        $form = $button.closest('form'),
        action = $form.attr('action');
}

当我们执行代码时,您将获得两个提交按钮,第一个用于第一个表单,第二个用于第二个表单。对于每个表单,在表单标签中指定了相应的操作,因为默认情况下方法未在表单标签中定义,它将认为这是一个请求 GET,您可以使用 $_REQUEST 或 $_GET 访问提交值。如果您需要一种安全的方式,您可以尝试使用 POST 并通过 $_POST.

访问所有值

例如:如果我们在 php 测试文件夹中执行上面的表单并提交你会得到这样的 http://localhost/test/website.com/controller?submitting=Submit

如果您在 html 中创建相同的内容并提交文件夹路径 "website.com/controller?submitting=Submit",这将被附加。

为了防止自动提交,您可以在表单中添加隐藏标记。

感谢大家抽出时间

最后一步:我想我不能使用 Ajax,因为每次我 POST,它都会得到最后生成的 formid 所以如果有 n 表单数量,每个提交按钮的 POST 看起来像:

http://website.com/controller?id=n

如果只有 1 个表格,那就不是问题了。但由于 form 次出现是可靠的,因此 AJAX 失败。

顺便说一句,这是我一直在使用的 Ajax 代码:

jQuery('form[name=someclass]).submit(function(e){
$.ajax({
        url: $('form[name=st_blog_comment_form]').attr('action'),
        type: 'POST',
        headers: { "cache-control": "no-cache" },
        dataType: 'json',
        data: $('form[name=someclass]').serialize(),
        cache: false,
        success: function(json){}
 )};

或许,我没有正确使用 ajax。