簡體   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