1. 程式人生 > >ajax的get和post(需修改)

ajax的get和post(需修改)

1:首先建立XMLHttpRequest物件:

2:向伺服器傳送請求

       xhr.open(a,b,c)

a:請求方式(get或者post)

b:請求地址(介面地址)

c:是否非同步(TRUE || FALSE)

      xhr.send()      向伺服器傳送的資料,post方式需要有傳送的資料

    xhr.onreadystatechange()監聽狀態碼改變,當狀態碼為4且頁面響應狀態status為200時觸發

 

get和post的ajax請求區別:

      post設定請求頭

     send()應該有傳遞給伺服器的資料

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>post</title>
	</head>
	<body>
    <input type="text" value="" />
		<input type="password" value="" />
		<input type="button" value="登入" />		
		<script type="text/javascript">
			window.onload = function(){
				var aInput = document.getElementsByTagName("input");				
				aInput[2].onclick = function(){
					var username = aInput[0].value;
					var pwd = aInput[1].value;
					var xhr = new XMLHttpRequest();
					xhr.open("POST","http://192.168.2.67:3000/api/user",true);
					xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
					xhr.send("name="+username+"&password="+pwd);
					xhr.onreadystatechange = function(){
						if(xhr.readyState == 4 && xhr.status == 200){
							console.log(xhr.responseText);	
						}
					}
				}
			}
		</script>
	</body>
</html>

    

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
    <script type="text/javascript">
			var xhr = new XMLHttpRequest();
			xhr.open("GET","http://192.168.2.67:3000/api/nowPlaying",true);
			xhr.send();
			xhr.onreadystatechange = function(){				
				console.log(xhr.readyState);			
				if(xhr.readyState == 4 && xhr.status == 200){			
					var data = xhr.responseText;				
					document.write(data);		
				}			
			}
		</script>
	</body>
</html>