介紹
<!--
ajax 無刷新技術
不刷新,部分刷新
1.頁面觸發,請求由頁面發起,ajax由js代碼實現
2.ajax也是符合http請求
3.XMLHttpRequest ajax請求的核心對象 存在瀏覽器兼容性 IE7開始支持這個對象
IE6 要使用 new ActiveXObject("Microsoft.XMLHTTP")
4.ajax請求是不刷新頁面的,請求是一次性的,不能使用轉發或者重定向
第一種直接請求業務,不返回任何東西到頁面
第二種請求業務得到結果數據,後臺一定要使用response.getWrite().print()獲取數據
第三種請求業務得到文件,音頻,視頻等等,後臺要使用response.getOutputStream()
5.ajax的同步和異步 ajax默認是異步 true ajax請求相當於開了一多線程
同步 false ajax就不是多線程,會順序運行
6.後臺傳遞到前臺不能傳遞對象只能傳遞字符串,如果要實現java和js中對象的互相轉換
要使用json
-->
<html>
<head>
<title>Title</title>
<script language="JavaScript">
function getName(){
//作ajax請求
//瀏覽器的兼容性
//1.獲取XMLHttpRequest對象
var xmlHttp;
if (window.XMLHttpRequest){
//如果存在 那瀏覽器是IE7以上
xmlHttp = new XMLHttpRequest();
}else{
//如果不存在,IE6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//請求
//2.準備請求的參數
//open方法 三個參數
//第一個參數請求的方法類型
//第二個參數請求的地址
//第三個參數請求是同步還是異步 默認是true
xmlHttp.open("get","MyServlet",true);
//擴展 ajax的回調函數
xmlHttp.onreadystatechange = function(){
// if(xmlHttp.readyState == 1){
// console.log("1、服務器連接已經建立");
// }
// if(xmlHttp.readyState == 2){
// console.log("2、請求已接受");
// }
// if(xmlHttp.readyState == 3){
// console.log("3、請求處理中");
// }
if(xmlHttp.readyState == 4 && xmlHttp.status==200){
console.log("後臺返回 回調函數");
console.log("4、請求已相應");
var data = xmlHttp.responseText;
console.log(data);
}
};
//3.發送請求
xmlHttp.send();
//4.獲取請求的結果 responseText請求結果
var data = xmlHttp.responseText;
console.log("請求結束");
}
</script>
</head>
<body>
<a href="MyServlet">獲取數據</a>
<form action="MyServlet">
<input type="submit" value="獲取數據">
</form>
<input type="button" value="觸發" onclick="getName()">
</body>
</html>
使用
$(function(){
$("#btn").click(function(){
var obj = {name:"xiaowang","sex":"男"};
$.ajax({
url:"MyServlet",
method:"get",
async:true,
data:"name=xiaowang&sex=男",
dataType:"text",
success:function(data){
alert(data);
}
});
});
});