如何使用PHP/Jquery实时从表单中获取输入



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

最新更新