1.下面是一个简单的php ajax 程序,你可以复制下来进行操作学习。
php代码:
<?php
$host ='127.0.0.1:3306';
$root ='root';
$password ='123456';
$dbname= 'Test';
$connect = mysql_connect($host,$root,$password,$dbname);
mysql_select_db("Test", $connect);//erp_database是库名
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
$name = $_POST['name'];
$password = $_POST['password'];
$login = mysql_query("select * from login where name ='".$name."' and password = '".$password."' ");
//$login = mysql_query("select * from login ");
$arr_login = mysql_fetch_array($login);
echo json_encode($arr_login);
?>
2.页面
<html>
<title>php+jquery+ajax+json简单小例子</title>
<?php
header("Content-Type:text/html;charset=utf-8");
?>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <!--导入包-->
<script type="text/javascript">
$(function() {
$("#subbtn").click(function() {
var params = $("input").serialize(); //得到输入框中的参数
var url = "login.php"; //需要跳转的路径。
$.ajax({
type: "post", //
url: url,
dataType: "json",
data: params, //以键/值对的形式 或着现在这个样子
success: function(msg){ //返回成功的的函数
var backdata = "您提交的姓名为:" + msg.name +
"<br /> 您提交的密码为:" + msg.password;
$("#backdata").html(backdata);
$("#backdata").css({color: "green"});
}
});
});
});
</script>
</head>
<body>
<p><label for="name">姓名:</label>
<input id="name" name="name" type="text" />
</p>
<p><label for="password">密码:</label>
<input id="password" name="password" type="password" />
</p>
<span id="backdata"></span>
<p><input id="subbtn" type="button" value="提交数据" /></p>
</body>
</html>