简体   繁体   English

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

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

I have a simple HTML form that includes an input field and a submit button.我有一个简单的 HTML 表单,其中包含一个输入字段和一个提交按钮。

How can I use JQuery to get the text from the input field live and then send that data to a PHP file that evaluates the data?我如何使用 JQuery 从输入字段中实时获取文本,然后将该数据发送到评估数据的 PHP 文件?

Form:形式:

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

Edit: here's what I want it to look like编辑:这是我想要的样子

    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>";

Your current code doesn't need jquery to get the text from the input field in PHP.您当前的代码不需要 jquery 即可从 PHP 中的输入字段获取文本。
When the user clicks on the Submit button, you can retrieve the text from the input with this code that you've to put in the file_that_will_process_data.php file当用户单击“提交”按钮时,您可以使用要放入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...
}

But if what you're looking for is to allow users to make something like a live search, you don't need the submit anymore.但是,如果您正在寻找的是允许用户进行实时搜索之类的操作,那么您就不再需要提交了。 Then you can do something like this using jquery:然后你可以使用 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