直接上代碼吧... 里面有注釋
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.4.1.js"></script>
</head>
<body>
<script>
(function() {
var data = {stuId:'4231'};
var list = [];
getInfo(function(data,obj){
// 第一次查詢沒有數據或者條數不滿足3條數據,進行參數分割
if( data ){
list.push(data);
}else{
// 參數分割
var stuIds = obj.stuId.split("");
// 循環請求獲取數據
for (var i = 0; i < stuIds.length; i++) {
// 參數對象
var obj = {stuId: stuIds[i]};
//先判斷 list 是否的條數 是否滿足條件
if( list.length >= 2 ){
// 中止請求
break;
//throw Error("滿足條件,不再進行請求...");
}else{
getInfo(function(data){
if( data ){
list.push(data);
}
},obj);
}
}
}
},data);
console.log(list);
})();
// 回調函數
function getInfo(callback,stuId) {
$.ajax({
async:false,// 同步請求
type: 'get', //請求方式
url: 'http://127.0.0.1:8080/stu/findById', //請求服務器地址
contentType: "application/json", //設置將要傳輸內容的編碼類型
data: stuId, //參數對象
success: function(data) { //完成時的事件
callback(data,stuId);
},
error: function(error) { //出現錯誤時的事件
alert("出現異常。");
}
});
}
</script>
</body>
</html>
