如何使用 ajax 请求从 php 获取值以输入

How to get value from php to input using ajax request

您好我的问题是如何使用带有 onclick 事件的 ajax 从 php 脚本中获取值。

我有一个文本字段和一个按钮

<button type="button" class="btn btn-primary" onclick="getid(this)">Generate ID</button>
<input type="text" name="pin" class="form-control" readonly>

这是我的 php 脚本,名为 getrowcount.php

include_once  'conx.php';

$query ="SELECT * FROM patientprofile";
$result = $DBcon->query($query);
$count = $result->num_rows;

if ($result) {
   if($count >= 0){
       $count_res = $count += 1;
       $idnum = $count_res;
       $test = str_pad($idnum, 5, "0", STR_PAD_LEFT);
    }
}

现在我的问题是如何从 $test 中获取值并使用 ajax.

将其放入输入文本字段中

为此,您 运行 在按下按钮时调用 ajax,从 ajax 加载 php,在 php 中执行echo 使用您要使用的变量,然后在 ajax 成功部分,您将使用返回的变量。

您可以在 javascript 脚本中使用 jQuery 方法 $.get() :

function getid(_this){
     $.get('php_script_url.php',{},function(response){
         alert(response);
         $("[name=pin]").val(response);
     })
}

然后在您的 PHP 脚本中,您应该将 echo 添加到您想要的结果中 return :

echo $test;

希望对您有所帮助。

您可以使用 AJAX 在输入字段中显示查询的输出。

第 1 步:将这行代码添加到 getrowcount.php 的底部:

echo $test;

第 2 步:修改您的 HTML 使其看起来像这样:

<form id="get">
   <input type="text" id="pin" name="pin" class="form-control" readonly>
   <input type="submit" class="btn btn-primary" value="Generate ID">
</form>

第 3 步:将此脚本添加到页面底部。

<script>
$(document).ready(function(){
    $("form#get").submit(function(event) {
        event.preventDefault();
        var input = $("#pin");

        $.ajax({
            type: "POST",
            url: "getrowcount.php",
            success: function(data) { input.val(data); }
        });
    });
});
</script>

也许这会对你有所帮助

您的 PHP 代码:

<?php
    // Your database query and results store in $test
    echo $test;
?>

你的 ajax 调用应该是 -

$.ajax("getrowcount.php").done(function(data) {
   $('.form-control').val(data);
})