繁体   English   中英

如何使用 PHP/Jquery live 从表单获取输入?

[英]How to get input from form using PHP/Jquery live?

我有一个简单的 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>";

您当前的代码不需要 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>

暂无
暂无

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

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