var myDate = new Date();
var myMonth = myDate.getMonth();
var myDate = myDate.getDate();
function getTitle() {
$.ajax({
headers: {
"apikey": "b56e70a91066a729d009b62cc16f9cb8",
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
type: 'get',
url: 'http://apis.baidu.com/avatardata/historytoday/lookup?yue=' + myMonth + '&ri=' + myDate + '&type=1&page=1&rows=20&dtype=JOSN&format=false',
data: {},
dataType: "json",
success: function(msg) {
var totalNum = msg.total;
var randomNum = Math.floor(Math.random() * totalNum + 1);
historyYear = msg.result[randomNum].year;
historyTitle = msg.result[randomNum].title;
alert(historyTitle);//这里显示全局变量的值正常。
$("#historyDate").text(historyYear + "年" + myMonth + "月" + myDate + "日");
$('#historyTitle').text(historyTitle);
},
error: function() {
alert("Error");
},
});
};
$(document).ready(function() {
getTitle();
alert(historyTitle);//这里显示的全局变量的值不正常,这是为什么?
$('#anotherThings').on('click', getTitle);
});
所有的代码在这里,供调试
getTitle
为异步函数,其中的 $.ajax
不阻塞。getTitle
返回时,success
函数还没被执行,因此此时无全局变量
Solution:
function getTitle () {
return $.ajax(...);
}
$(function () {
getTitle()
.done(function () {
alert(<GLOBAL_VARIABLE>)
}
getTitle(); 里面的ajax异步呀,“alert(historyTitle);//这里显示的全局变量的值不正常,这是为什么?” 或许ajax还没返回东西呢
1、你的getTitel()执行的ajax请求,是异步的,调用完getTitle时,实际上请求并未完成,还未给history赋值,解决方案1:将ajax请求改为同步请求,方案2,在ajax请求的success()方法中执行,你要做的业务处理