ajax的return要特別注意寫法,用變數接回再傳

$(function () {
    var console.log(testGetResult());   // 抓不到預期的boolean , show undefined
	var console.log(testGetResult2());  // show true or false
});

function testGetResult() {
	$.ajax({
        url: '/getData.do',
        type: 'get',
		async: false,
		success: function (res) {
            return true;
        },
        error: function (res) {
            return false;
        }
    });
}

function testGetResult2() {
	var rtn;
    $.ajax({
        url: '/getData.do',
        type: 'get',
		async: false,
		success: function (res) {
            rtn = true;
        },
        error: function (res) {
            rtn = false;
        }
    });
	return rtn;
}
arrow
arrow

    咪卡恰比 發表在 痞客邦 留言(0) 人氣()