我在服务器上有一个简单的数据库(用于测试)。此PHP文件位于服务器上,当我打开URL时可以工作。(.com/search.php?id=abc)回声回馈"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>我希望当我在Textfield中输入一个代码并按下Button时,PHP中的Echo将显示在Div中。我知道我应该使用Ajax,但是我尝试了太多的东西,但是没有什么效果。能帮我一下吗?
编辑:最后一次尝试: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,我只是抄袭了所有的第一次尝试:
发布于 2017-04-09 13:17:30
您可以使用一个简单的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());
}我认为这应该有效(还没有测试过)。如果它不起作用,让我知道,我会测试和纠正它。
https://stackoverflow.com/questions/43300779
复制相似问题