天天看點

ajax請求404_AJAX相關使用案例

ajax請求404_AJAX相關使用案例
AJAX

即“

A

synchronous

J

avascript

A

nd

X

ML”(異步 JavaScript 和 XML),

是指一種是一種用于建立快速動态網頁的技術。

使用步驟 :

【1】建立AJAX引擎

var xhr = new XMLHttpRequest();

【2】建立HTTP請求

xhr.open(method, url, async, username, password)

//第一個參數method:http請求方式

//第二個參數url:http請求位址

//第三個參數async:表示是否異步請求

//第四個和第五個參數username和password:用于提供http驗證機制

【3】發送請求

//如果不發送額外的請求資料,send()方法可以不傳參數

xhr.send()

【4】處理背景傳回的資料(監聽readyState值的變化)

xhr.onreadystatechange = function() { }

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" target="_blank" rel="external nofollow" >
<title>My JSP 'xhr_obj.jsp' starting page</title>
<script type="text/javascript">

	function doAjax(){
		//1.建立ajax引擎
		var xhr = new XMLHttpRequest();
		
		//4.監聽readyState的值,
		//隻要當readyState的值發生了變化,就調用綁定在onreadystatechange(請求狀态改變的事件)上面的函數
		xhr.onreadystatechange = function(){
			console.log("-----------"+xhr.readyState+"-----------")
			
			//readyState等于4就表示伺服器已經和ajax引擎互動完成,資料已經在ajax引擎中了!
			if(xhr.readyState == 4){
				//status 表示http狀态碼
				if(xhr.status == 200){
					//伺服器響應的文本:responseText
					//對傳回的資料使用DOM進行操作
					if(xhr.responseText == "true"){
						document.getElementById("myDiv").innerHTML = "使用者名已存在"
					}else{
						document.getElementById("myDiv").innerHTML = "使用者名可用"
					}
				}else if(xhr.status == 404){
					window.loaction.href="404.html" target="_blank" rel="external nofollow" ;
				}else if(xhr.status == 500){
					document.getElementById("myDiv").innerHTML="伺服器正在開了一個小差,請過會再試!"
				}
			}else{
				document.getElementById("myDiv").innerHTML = "資料加載中..."
			}
		}
		
		//2.建立一個http請求
		//第一個參數method:http請求方式
		//第二個參數url:http請求位址
		//第三個參數async:表示是否異步請求
		//第四個和第五個參數username和password:用于提供http驗證機制
		xhr.open("get", "hiservlet", true);
		
		//3.發送http請求
		//如果不發送額外的請求資料,send()方法可以不傳參數
		xhr.send()
	}

</script>
</head>
<body>
	<button onclick="doAjax();">發送ajax請求</button>
	
	<div id="myDiv">請求的資料為:</div>
</body>
</html>