【问题标题】:How to get input from form using PHP/Jquery live?如何使用 PHP/Jquery live 从表单获取输入?
【发布时间】:2020-11-11 16:36:00
【问题描述】:

我有一个简单的 HTML 表单,其中包括一个输入字段和一个提交按钮。

如何使用 JQuery 从输入字段实时获取文本,然后将该数据发送到评估数据的 PHP 文件?

表格:

<form action='file_that_will_process_data.php' method='POST'>
<input id='text' type='text' name='txt'>
<button type='submit'>Submit</button>
</form>

编辑:这是我想要的样子

    echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>';
    echo "<script>$(function() {
        $('button').on('click', function() {
          var txt = $('#txt').val();
        sendTextTo_file_that_will_process_data_AndReturnTheValueThat_file_that_will_process_dataReturns(txt)
      })</script>";

【问题讨论】:

    标签: javascript php html jquery forms


    【解决方案1】:

    您当前的代码不需要 jquery 从 PHP 的输入字段中获取文本。
    当用户单击提交按钮时,您可以使用您必须放入 file_that_will_process_data.php 文件的代码从输入中检索文本

    <?php 
    if (isset($_POST['txt'])) {
        var_dump($_POST['txt']); // $_POST['txt'] contains the text from the input field
        // TODO: make your treatment here...
    }
    

    但是,如果您正在寻找的是允许用户进行实时搜索之类的操作,那么您就不再需要提交了。然后你可以使用 jquery 做这样的事情:

    $(function() {
      $('input[name="txt"').on('keyup', function() {
        const $form = $(this).closest('form');
        $.ajax({
          type: "POST",
          url: $form.attr('action'),
          data: {
            txt: $(this).val()
          },
          success: function (data) {
            // data contains the result of your treatment in the file_that_will_process_data.php file. Do whatever you want with it here
          }
        })
      })
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form action='file_that_will_process_data.php' method='POST'>
        <input type='text' name='txt'>
        <button type='submit'>Submit</button>
    </form>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 2018-02-18
      • 2010-09-15
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多