【问题标题】:How to fill input fields with an ajax request from MySQL server using PHP?如何使用 PHP 使用来自 MySQL 服务器的 ajax 请求填充输入字段?
【发布时间】:2020-03-01 13:19:22
【问题描述】:

我有一个输入字段,我正在尝试使用 PHP 向我的 SQL 服务器填充 AJAX 请求,但它不起作用。 console.log 吐出正确的数组标题:“” 描述:“”,但它不会将数据添加到文本输入字段,所以我可以看到它。我看过其他答案,但还不够。谢谢!
HTML

<input type="text" class="inputtext" name="task-title-reg" value="">
<textarea class="textbox" name="task-description-reg" rows="4" cols="50" value=""></textarea>

AJAX 请求

                $(".task-listing").click(function() {
                $.ajax({
                    type: 'POST',
                    url: 'task-info-get.php',
                    dataType: 'json',
                    data: 'pid=' + $(this).attr("id"),
        success: function (response) {
            console.log(response);
            $("task-title-reg").val(response);
            $("task-description-reg").val(response);
        }
                })
            });
            });

PHP

<?php
include 'sqlconnection.php';
$conn = OpenCon();

$stmt = $conn->prepare('SELECT title,description FROM tasks WHERE pid='.$_POST['pid']);
$stmt->execute();
$stmt->bind_result($title,$description);
while($stmt->fetch()) {
    $output[]=array(
        'title' => $title,
        'description' => $description

    );
}
$json=json_encode($output);
echo $json;

$stmt->close();
CloseCon($conn);
?>

【问题讨论】:

  • #$task-title-reg $ 在这里做什么?
  • 这正是我一直在尝试的。我现在删除了它们
  • 你知道$('#通过id属性选择标记元素吗?
  • 这就是我的想法,我只是尝试使用“.task-title-reg”和“task-title-reg”无济于事
  • 这里有一些问题。 1)$("task-title-reg") 不是一个有效的选择器,使用例如$('.inputtext')(你的文本区域也有同样的问题); 2) ....val(response); - 您的 response 是一个 JSON 对象,您只需要每个输入字段中的一个元素。试试.val(response.title);,类似的描述。 3) $output[]=array(..) - 创建一个多维数组,这里不需要。 $output=array(...) 就够了。

标签: php jquery html mysql ajax


【解决方案1】:

我建议你使用类来输入值。

$('.inputtext').val('Your value here!')

【讨论】:

  • 它只是说 [object Object] 如果我这样做 $('.inputtext').val(response);我需要从对象转换为...?
【解决方案2】:
$json=json_encode($output);
echo $json;

由于上面的代码和dataType:'JSON',响应是javascript对象。

通过向javascript对象提供keys来访问字符串:

function (response) {
            console.log(response);
            $(".task-title-reg").val(response.title);
            $(".task-description-reg").val(response.description);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多