html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<?php header("content-type :text/html;charset=utf-8");?>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<form action="PDO_insert.php" method="post">
Name: <input type="text" name="name" id="name"/>
<input type="submit" value='查询' id="btn"/>
</form>
<script type="text/javascript">
Variablenname =document.getElementById('name').value;
$("#btn").on("click", function () {
$.ajax({
type: "POST",
url: „PDO_insert.php“,//url放的是当前页面请求的后台地址.
data:{name:name},
async:false,
dataType: „json“,
Erfolg: Funktion (Daten) {
var result=data;
//var result = eval('[' + data + ']');
Alert(result);
},
Fehler: Funktion () {
Alert("请求失败!");
}
});
});
</script>
</body>
</html>
<?php
$host =. 'local host';
$ Datenbank = 'test';
$username = 'root';
$password = 'root';
$selectName = $_POST['name'];
$pdo = new PDO("mysql: host=$host;dbname=$database", $username, $password);//创建一个pdo对象
$pdo->exec("setnamen 'utf8'");//设置数据库编码
$ sql = "select * from user where name = ?";
//$sql = "select * from user";
$stmt = $pdo->prepare($sql);
$rs = $stmt ->execute(array($selectName));
if ($rs){
// PDO::FETCH_ASSOC 关联数组形式
// PDO::FETCH_NUM 数字索引数组形式
während ( $row = $stmt->fetch(PDO::FETCH_ASSOC)) {
global $name,$age;
$name = $row['name'];
$age = $row['age' ];
}
}
$data='{name:"'.$name.'",age:"'.$age.'"}';
echo json_encode($data); //打印出:"{name:"1",age:"1"}"
?>
为什么每次获取的都是前一次查询的数据?
你这是相当于两次查询,第一次是form查询,第二次是ajax查询,你把<input type="submit" value='查询' id="btn"/>这个放form外面试试