gpt4 book ai didi

javascript - 使用 Ajax 从 PHP 获取 Echo 到 Div

转载 作者:行者123 更新时间:2023-11-30 22:01:10 25 4
gpt4 key购买 nike

我在服务器上有一个简单的数据库(用于测试)。这个 PHP 文件在服务器上,当我打开 URL 时它可以工作。 (http://**.com/search.php?id=abc) Echo 返回“30”

<?php
$pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*');
$idV = $_GET['id'];
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = :idV");
$statement->bindParam(':idV', $idV);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{ $posV = $row['position']; };
echo $posV;
?>

HTML 仅用于测试

<input type="text" id="txt1">
<button type="button" class="btn btn-info" id= "bt1">Info Button</button>
<div id= "div1"> </div>

我希望当我在文本字段中输入代码并按下按钮时,来自 PHP 的 Echo 会显示在 Div 中。我知道我应该使用 Ajax GET,但我尝试了很多东西,但没有任何效果。你能帮我吗?

编辑:上次尝试:https://jsfiddle.net/qz0yn5fx/

    <input type="text" id="txt1">
<button type="button" class="btn btn-info" id="bt1">Info Button</button>
<div id="div1">Here </div>

<script>
$(document).ready(function() {

$("#bt1").click(function() {
$.ajax({
//create an ajax request to load_page.php
type: "GET",
url: "http://**.com/search.php?id=a10 ",
dataType: "html", //expect html to be returned

success: function(response){
$("#div1").html(response);
alert(response);
}

});
});
});
</script>

最好不要看下一个 Fiddle,我刚刚复制了所有第一次尝试:

https://jsfiddle.net/jqv1ecpj/

最佳答案

您可以只使用简单的 POST 请求而不是 GET 请求。

  <form id="search" name="search" method="post">
<input type="text" id="txt1" name="search_input">
<button type="submit" class="btn btn-info" id="bt1">Info Button</button>
</form>
<div id="div1">Here </div>

$(document).ready(function(){
$("#search").on("submit", function(e){
e.preventDefault();
$.post("/search.php", $("#search").serialize(), function(d){
$("#div1").empty().append(d);
});
});
});

然后在您的 PHP 中,(不要忘记使用 try{}catch{}):

    try {
$pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$idV = (isset($_POST['search_input'])) ? $idV = $_POST['search_input'] : exit('The search was empty');
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->bindParam(1, $idV);
$statement->execute();
foreach($statement -> fetchAll() as $row){
echo $row['position'];
}

$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}

我认为这应该可行(尚未测试)。如果它不起作用,请告诉我,我会测试并更正它。

关于javascript - 使用 Ajax 从 PHP 获取 Echo 到 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43300779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com