Home  >  Q&A  >  body text

$.ajax() gets background data

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">

        var name=document.getElementById('name').value;

$("#btn").on("click", function () {

$.ajax({

type: "POST",

url: "PDO_insert.php",//url放的是当前页面请求的后台地址。

data:{name:name},

async:false,

dataType: "json", 

success: function (data) {

var result=data;

//var result = eval('[' data ']');

alert(result);

},

error: function () {

alert("请求失败!");

}

});

});

</script>

</body>

</html>



<?php 


$host = 'localhost';

$database = 'test';

$username = 'root';

$password = 'root';

$selectName = $_POST['name'];

$pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);//创建一个pdo对象

$pdo->exec("set names '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 数字索引数组形式

while ($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\"}"

?>

为什么每次获取的都是前一次查询的数据?

等一个人等一个人2053 days ago1311

reply all(3)I'll reply

  • 三言

    三言2019-03-06 17:09:28

    You are equivalent to two queries, the first is a form query, the second is an ajax query, you put <input type="submit" value='query' id="btn"/> this Try putting it outside the form

    reply
    0
  • 等一个人

    I tried it, but the PHP code will not execute.

    等一个人 · 2019-03-06 17:13:10
  • Cancelreply