ajax传递数据显示在前端指定位置

reg.html

<!DOCTYPE HTML>
<html>
	<head>
		<title> ajax </title>
		<meta charset="utf-8"/>
		<script type="text/javascript">
			var httpAjax = new XMLHttpRequest();
			function checkUser(uname){
				if(uname == ""){
					return false;
				}
				httpAjax.onreadystatechange = function(){
					if(httpAjax.readyState == 4 && httpAjax.status == 200){
						var res = httpAjax.responseText;
						res = eval("("+res+")");
						var sp = document.getElementById("sp");
						if(res.status == 1){
							  sp.innerHTML = "<font color='red'>"+res.info+"</font>";
							  var _html ="";
							  for(var i in res['data']){
							  		_html += "<p>"+res['data'][i]+"</p>"
							  }
							  var myobject = document.getElementById('mydiv');
							  myobject.innerHTML = _html;
						}else{
							sp.innerHTML = "<font color='green'>"+res.info+"</font>";
						}
					}
				}
				httpAjax.open("post","user.php",true);
				httpAjax.setRequestHeader("content-TYPE","application/x-www-form-urlencoded");
				var data = "uname="+uname; //user.php?uname="1"&pwd="123","uname=" 是参数,+是连接参数连接变量的用的,uname是js中的一个不带$的变量,也就是值
				httpAjax.send(data);
			}

		</script>
	</head>
	<body>
		<input type="text" id="username" class="username" name="username" onchange="checkUser(this.value)"/><span id="sp"></span>
		<div  id ="mydiv" style="width:200px;height:200px;border:1px red solid">
			
		</div>
	</body>
</html>


user.php

<?php
	header("content-type:text/html;charset=utf-8");
	$pdo = new PDO("mysql:host=localhost;dbname=tk106","root","");
	$pdo->exec("set names utf8");
	$uname = $_REQUEST["uname"];//post传值,这里要改为REQUEST
	$sql = "select * from stu_info where sname='".$uname."'";
	$data = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
	if($data){
		 $list['status']=1;
		 $list['info']="已经注册";
		 $list['data']=$data;
		 echo json_encode($list);
	}else{
		 $list['status']=0;
		 $list['info']="未注册";
		 $list['data']=="";
		 echo json_encode($list);
	}
?>


你可能感兴趣的:(Ajax)