$.ajax使用方法
常用參數(shù):
1、url 請求地址
2、type 請求方式,默認是'GET',常用的還有'POST'
3、dataType 設置返回的數(shù)據(jù)格式,常用的是'json'格式,也可以設置為'html'
4、data 設置發(fā)送給服務器的數(shù)據(jù)
5、success 設置請求成功后的回調函數(shù)
6、error 設置請求失敗后的回調函數(shù)
7、async 設置是否異步,默認值是'true',表示異步
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
<style type="text/css">
</style>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'js/data.json',//請求的服務器路徑,實際開發(fā)中寫文檔接口的路徑
type: 'get',//分get/post請求,涉及隱私或安全性要求較高的用post、安全要求不高及數(shù)據(jù)量較小的用get
dataType: 'json',//要讀取什么格式的數(shù)據(jù),還可以是xml script html upload等
// data:{page:1}//請求時要攜帶的參數(shù)
})
.done(function(data){//成功的時候會執(zhí)行的函數(shù),參數(shù)data是從后臺接收到的數(shù)據(jù),這里是json格式的字符串
alert(data.name);
console.log(data);
})
.fail(function(){//失敗的時候會執(zhí)行的函數(shù)
console.log("error");
})
/*
.fail(function(XMLHttpRequest, textStatus, errorThrown) {//失?。◣?shù))
console.log("error");
// 狀態(tài)碼
? ? ? ? ? ? console.log(XMLHttpRequest.status);
? ? ? ? ? ? // 狀態(tài)
? ? ? ? ? ? console.log(XMLHttpRequest.readyState);
? ? ? ? ? ? // 錯誤信息?
? ? ? ? ? ? console.log(textStatus);
})
.always(function(){//不論成功與否都會執(zhí)行
console.log("always");
})
*/;
</script>
</head>
<body>
</body>
</html>