【发布时间】:2015-07-08 00:44:47
【问题描述】:
我知道是异步,但是我按照添加回调函数的步骤Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 但是我只能访问回调函数内部的更改。这是我的代码 sn-p。请帮忙
function callback(point) {
for (i = 0; i < point.length; i++) {
myDate[i] = point[i].date_time;
myValue[i] = point[i].my_value;
}
for (j = 0; j < myDate.length; j++) {
var temp = new Array(myDate[j], myValue[j]);
mySeries[j] = temp;
}
alert("MYSERIES in scope: " + mySeries); //defined
}
alert("MYSERIES out scope: " + mySeries); // undefined
getAllMessagesforChart(callback);
function getAllMessagesforChart(callback) {
var data = @Html.Raw(JsonConvert.SerializeObject(this.Model))
$.ajax({
url: '/messages/GetMessagesforChat',
data: {
id: data.id,
},
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'JSON'
}).success(function (data) {
callback(data);
}).error(function (e) {
alert("error " + e)
})
}
【问题讨论】:
-
这是因为它不是“之后”。
-
您是否好奇为什么您的
mySeries变量在callback函数之外未定义? -
是的,我是新手,我需要帮助
-
好吧,你自己回答了,它超出了范围。您在
callback中定义了它。如果你在函数外添加var mySeries;,那么作用域就是全局的,你可以看到它。
标签: jquery ajax asynchronous