原生ajax
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<input type="text" name="user" id="a1">用户
<input type="password" name="password" id="a2">密码
<input type="button" value="提交" id="a3">
<p id="a4">结果:</p>
<script type="text/javascript">var us=document.getElementById("a1");var pa=document.getElementById("a2");var btn=document.getElementById("a3");btn.onclick=function () {if(us.value==""||us.value==null){alert("用户名为空,请重新输入")}if(pa.value==""||pa.value==null){alert("密码为空,请重新输入")}if(us.value!=""&&pa.value!="") {var xhr = new XMLHttpRequest();xhr.onreadystatechange = function () {if (xhr.readyState !== 4) {return;}if (xhr.status >= 200 && xhr.status <= 300){document.getElementById("a4").innerHTML=xhr.responseText;//从后台获取值输出到页面}else {console.log("false");}}//配置对象xhr.open('post', './1.php', true);//设置请求头,指定body的数据是何格式xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');//发送数据xhr.send("user="+ us.value + "&" + "password="+pa.value);}}</script>
</body>
</html>
输入前
输入后
注意输入的用户名为:wowo 密码为 123456,测试才有效果
因为我已经把数据库里提取的用户名和密码的值设为这两个
后台
<?php
$user=$_POST['user'];
$password=$_POST['password'];
if($user=='wowo'&&$password=='123456')
{echo $user.'</br';echo $password.'</br';
}
else
{echo "false";
}?>
jQuery中的ajax
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<input type="text" name="uesr" id="a1"/>用户名
<input type="password" name="password" id="a2"/>密码<input type="button" name="button" id="a3"/>提交
<p id="aa"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">$("#a3").click(function () {var user1 = $("#a1").val();var pass=$("#a2").val();if(user1==""||user1==null){alert("false");}else if(pass==""||pass==null){alert("false");}else{alert("ok");$.ajax({url:'jqueryshizhan.php',//发送请求的地址type:'post', //请求方式,默认为GETdataType:'json',//预期服务器返回的数据类型,String类型的参数;可用类型有(xml,html,json,jsonp,text)data:{'name':user1, //发送到服务器的数据,Object或String类型的参数,如果已经不是字符串,将自动转换为字符串格式。'name1':pass},success:function (msg) {$("#aa").append(msg.name+" gg "+msg.name1);//回调函数输出}});}})</script>
</body>
</html>
效果图
输入前
输入后
gg是我用来测试的字符串,不用管它
后台代码
<?php
$user=$_POST['name'];
$password=$_POST['name1'];
$json_array = array('name'=>$user,'name1'=>$password );
$json= json_encode($json_array); //将数组转换成json对象
echo $json;
?>