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);
	}
?>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章