繁体   English   中英

如何通过AJAX从页面上具有多个表单的表单中发送数据?

[英]How to send data from one form on a page with multiple forms through AJAX?

index.php

    <script>
$(document).ready(function(){
  $("form").submit(function(){
   var str = $(this).serialize();
  $.ajax({
     type: "POST",
     url:"do.php",
     data: $("form").serialize(), 

  });
  return false;
 });
});
</script>

    <form action='do.php' method='post' id='toDo' name='toDo'>
        <input type='hidden' name='okok' value='one.txt'>
        <button type='submit' class='theButton'></button>
    </form>

    <form action='do.php' method='post' id='toDo' name='toDo'>
        <input type='hidden' name='okok' value='two.txt'>
        <button type='submit' class='theButton'></button>
    </form>

在上面的代码中,有2种不同的形式-每个都具有相同的名称。 每个表单都有一个input hidden标签,它具有与目录中特定文件相关的唯一值。

如果用户单击任何表单中的“提交”按钮,则用户单击了“提交”按钮的表单中的input hidden标签的值将发送到文件do.php中

由于input hidden标签的值是文本文件的名称,因此将其发送到do.php (如下所示)后,将检索文件的内容(内容均为数字)。 从文本文件中检索到的值(数字)将增加1。增加1的新值将重写旧值并存储在文本文件中。

do.php

<?php
    $filename = $_REQUEST[okok];
    $content = file_get_contents($filename);
    preg_match("#\d+#", $content, $before_editing);
    $number_before = $before_editing[0];
    file_put_contents($filename, ++$number_before);

    $content = file_get_contents($filename);
    preg_match("#\d+#", $content, $after_editing);
    $number_after = $after_editing[0];   
?>

该代码可以在没有我包含的AJAX脚本的情况下完美运行。 使用AJAX脚本,仅将底部表单的值发送到do.php-因此,如果我在第一个表单上单击Submit ,则将发送值two.txt而不是发送值one.txt

我将如何修复AJAX以使其正常工作?

这是问题所在:

data: $("form").serialize(),

此代码查找并序列化DOM中的所有表单元素,而不仅仅是您想要的元素。 快速解决:

$(document).ready(function(){
    $("form").submit(function(){
        var str = $(this).serialize();
        $.ajax({
            type: "POST",
            url:"do.php",
            data: $(this).serialize(), // serialize only clicked form, not both
        });
        return false;
    });
});

请注意,您的代码中存在各种安全问题,包括路径遍历漏洞。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM