php 单击按钮时使用 ajax 获取文本框文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16160456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:37:35  来源:igfitidea点击:

Get the textbox Text using ajax on button click

phpjavascriptajax

提问by Niranjana668

I want a code for get textbox value when submit button is clicked. It must be Ajax.Here is the code I tried so far.But I culdent get to work....

我想要一个代码,用于在单击提交按钮时获取文本框值。它必须是 Ajax。这是我到目前为止尝试过的代码。但我已经开始工作了......

<form action="" method="post">
<p>Route No :
<input type="text" name="route_no" required="required" />
<input type="submit" value="Search" name="search" />
</form>

Ajax Code

阿贾克斯代码

<script type="text/javascript">
$(document).ready(function() {
$("#sub").click(function() {
var textboxvalue = $('name or id of textfield').val();
$.ajax({
    type: "POST",
    url: 'ajaxPage.php',
    data: {txt1: textboxvalue},
    success: function(result) {
        $("div").html(result);
    }
});
});
});?
</script>

PHP code

PHP代码

$txt = null;
if((isset($_POST)) && (isset($_POST['txt1'])))
{
echo $txt = $_POST['txt1'];
}

回答by SimonDever

HTML:

HTML:

<label for="route_no">Route No:</label><input type="text" id="route_no" name="route_no" required="required" />
<input type="button" value="Search" id="search" />
<div id="result"></div>

JavaScript:

JavaScript:

$(document).ready(function()
{
    $("#search").click(function()
    {
        var textboxvalue = $('input[name="route_no"]').val();

        $.ajax(
        {
            type: "POST",
            url: 'ajaxPage.php',
            data: {txt1: textboxvalue},
            success: function(result)
            {
                $("#result").html(result);
            }
        });
    });
});?

ajaxPage.php:

ajaxPage.php:

if(isset($_POST) && isset($_POST['txt1']))
{
    echo $_POST['txt1'];
}

回答by chandresh_cool

You have problem here

你这里有问题

$("#sub").click(function() {

you are using id ="sub" for submit button but you are not assigning id to that button so give id to submit button as id="sub".

您正在使用 id ="sub" 作为提交按钮,但您没有为该按钮分配 id,因此将提交按钮的 id 指定为 id="sub"。

回答by Mariano

To get the value of the textbox you can use:

要获取文本框的值,您可以使用:

$('#elementid').val()