Ajax简易异步注册demo
例 reg.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax请求Demo</title>
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<tr>
<td>用户名:</td>
<td><input type="text" name="username" id="username">
</td>
</tr>
<tr>
<td>年 龄:</td>
<td><input type="text" name="age" id="age"></td></tr>
<tr><td colspan="2" class="text-center"><input type="button" id="reg" name="reg" value="注册"></td></tr>
</table>
</div>
<script>
$("#reg").click(function(){ //获取注册按钮单击事件
var username=$("#username").val(); //获取用户名文本框值
var age=$("#age").val(); //获取年龄文本框值
$.ajax({
type:"post", //设置为POST传输入方式
url: "http://localhost/conn.php", //请求处理地址
data: {username:username,age:age}, //json数据
success: function(data,status){ //回调函数返回状态
console.log("数据"+data+"\n状态"+status); //输出返回状态
}});
})
</script>
</body>
</html>
conn.php //文件名自定义
<?php
header("Content-Type:text/html;charset=utf-8");
$username=$_POST["username"];
$age=$_POST["age"];
try{
$conn = new PDO("mysql:host=localhost;dbname=users","root","root");
$conn->query('set names utf8');
$sql = "INSERT INTO user (username, age) VALUES(?,?)";
$result = $conn -> prepare($sql);
$res = $result -> execute(array($username,$age));
// var_dump($res);
}catch(PDOException $e){
die("数据库连接错误!原因:".$e->getMessage());
}
$conn = null;
?>